Python:Classes: Difference between revisions

From wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 1: Line 1:
Create your own classes
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>)
;__init__(self, <parameters that can be provided with default value>)
:Constructor, automatically called when the object is instantiated.
:Constructor, automatically called when the object is instantiated.


;self
;__del__(self)
:The namespace of the current instance. Can have any name, 'self' is commonly used.
:Destructor, automatically called when the object is removed.
 


;__str__(self)
;__str__(self)

Revision as of 14:19, 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()]