Difference between revisions of "Python:Classes"
Jump to navigation
Jump to search
m |
|||
Line 6: | Line 6: | ||
;__init__(self) | ;__init__(self) | ||
:Constructor, automatically called when the object is instantiated. | :Constructor, automatically called when the object is instantiated. | ||
+ | |||
+ | Example: | ||
+ | <syntaxhighlight lang=python> | ||
+ | class Medium: | ||
+ | def __init__(self, titel='', prijs=0): | ||
+ | self.titel = titel | ||
+ | self.prijs = prijs | ||
+ | |||
+ | def __str__(self): | ||
+ | return "Titel: {0}\nPrijs: {1:6.2f}".format(self.titel,self.prijs) | ||
+ | |||
+ | def gettitel(self): | ||
+ | return self.titel | ||
+ | |||
+ | def settitel(self, titel): | ||
+ | self.titel = titel | ||
+ | |||
+ | def getprijs(self): | ||
+ | return self.prijs | ||
+ | |||
+ | def setprijs(self,prijs): | ||
+ | self.prijs = prijs | ||
+ | |||
+ | def getall(self): | ||
+ | return [self.gettitel(),self.getprijs()] | ||
+ | </syntaxhighlight> |
Revision as of 13:25, 15 March 2018
Create your own classes
Classes should have
- __init__(self)
- Constructor, automatically called when the object is instantiated.
Example:
class Medium:
def __init__(self, titel='', prijs=0):
self.titel = titel
self.prijs = prijs
def __str__(self):
return "Titel: {0}\nPrijs: {1:6.2f}".format(self.titel,self.prijs)
def gettitel(self):
return self.titel
def settitel(self, titel):
self.titel = titel
def getprijs(self):
return self.prijs
def setprijs(self,prijs):
self.prijs = prijs
def getall(self):
return [self.gettitel(),self.getprijs()]