Difference between revisions of "Python:Classes"

From wiki
Jump to navigation Jump to search
Line 1: Line 1:
 
Create your own classes
 
Create your own classes
  
Classes should have
+
;__init__(self, <parameters that can be provided with default value>)
 +
:Constructor, automatically called when the object is instantiated.
  
 +
;self
 +
:The namespace of the current instance. Can have any name, 'self' is commonly used.
  
;__init__(self)
+
;__str__(self)
:Constructor, automatically called when the object is instantiated.
+
: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:
 
Example:

Revision as of 13:54, 15 March 2018

Create your own classes

__init__(self, <parameters that can be provided with default value>)
Constructor, automatically called when the object is instantiated.
self
The namespace of the current instance. Can have any name, 'self' is commonly used.
__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()]