Variabelen (Python)
Variabelen moeten eerst geïnitieerd worden
Dit
#!/usr/bin/python3 print(MijnGeheimeVariabele)
geeft foutmelding
NameError: name 'MijnGeheimeVariabele' is not defined
Dit geldt ook voor attributen van een klasse. Simpele oplossing: Variabelen initiëren in de constructor (?) van die klasse.
Print & variabelen
#!/usr/bin/python3 # Met cijfers ############# # lucky=7 print (lucky) # Met strings ############# # lucky="Hallo" print(lucky) # Je kunt variabelen niet embedden in een string zoals in Bash ############################################################## # print("En hier komt lucky voorbij") print("En hier komt $lucky voorbij")
Dictionaries
Voorbeeld:
>>> d={"stad":"Amsterdam", "stad":"Rotterdam"} >>> d {'stad': 'Rotterdam'}
Zie https://en.wikibooks.org/wiki/Python_Programming/Dictionaries voor meer.
Init
Voorbeeld van initialization of init:
#! /usr/bin/python3 # ############################################################################## class Foo: "Here is an explanation about the foo class" def __init__(self): print("The world is an instance of Foo richer!") self.x=0 # Init var x + set to 0 ############################################################################## # __init__ ############################################################################## # f=Foo() print(f.x)
Output:
The world is an instance of Foo richer! 0
Als de regel met self.x=0
wordt uit-gecommentariseerd, krijg je als output:
The world is an instance of Foo richer! Traceback (most recent call last): File "./klasse-03.py", line 36, in <module> print(f.x) AttributeError: 'Foo' object has no attribute 'x'
Interessant: Het script wordt wel uitgevoerd tot aan het probleem.