Difference between revisions of "Python:Classes"
Jump to navigation
Jump to search
m |
|||
Line 9: | Line 9: | ||
;__del__(self) | ;__del__(self) | ||
:Destructor, automatically called when the object is removed. | :Destructor, automatically called when the object is removed. | ||
− | |||
;__str__(self) | ;__str__(self) |
Revision as of 16:20, 20 March 2018
Create your own classes
- self
- The namespace of the current instance. Can have any name, 'self' is commonly used.
- __init__(self, <parameters that can be provided with default value>)
- Constructor, automatically called when the object is instantiated.
- __del__(self)
- Destructor, automatically called when the object is removed.
- __str__(self)
- Returns the string representation of the object. E.g. if you use print(object) or str(object)
All interaction with the object should go via a method, not to variables in the class.
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()]