OO (Python)

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen

Python is een object oriented programmeertaal. Hoe werkt dat ook al weer?

Voorbeeld: Zelfs een string is een object

>>> mijnobject = "hallo"
>>> print(mijnobject)
hallo

>>> print(mijnobject.upper())
MIJNOBJECT

Klasses

  • De class of klasse van een object, is de definitie, blauwdruk, sjabloon of template om nieuwe exemplaren van dat object te instantiëren. De klasse-aanroep geschiedt hier impliciet - Simpelweg door de string te instantiëren
  • Algemener: Een klasse is de defintie van een verzameling samenhangende gegevens en functies [1].

Attributen & methods

Hierboven zie je de aanroep print(mijnobject.upper()). Ik zou denken dat dat een method is, oftewel een functie die bij een object hoort. Het voorbeeld hieronder geeft echter aan, dat dit een attribuut betreft. Ik denk dat het 't beste is, als ik me daar niet al te druk om maak:

>>> print 'myobject'.mijnfantasieding()
AttributeError: 'str' object has no attribute 'mijnfantasieding'

Alle methods achterhalen

Tjakka:

>>> dir(mijnobject)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Voorbeelden:

>>> print(mijnobject.isprintable)
<built-in method isprintable of str object at 0x7f1bbf3eafb8>   # Zonder () achter de method, krijg je alleen info *over* de method

>>> print(mijnobject.isprintable())   # Method of property? Misschien maakt het niet uit
True

>>> print(len(mijnobject))   # Geem method, maar een 'externe' functie
5

Mijn eerste klasse

#! /usr/bin/python3
#
##############################################################################

class Foo:
    "Here is an explanation about the foo class"

    def helloworld(self): # A method is a function within a class
    	print ("Hello, world! - Greetings from foo")

    def bye_world(self):
    	print ("Bye, world! - Greetings from foo")

    def setx(self, x):   # x is a member 
    	self.x =x

    def printx(self):
    	print (self.x)

    def reset_x(self):
    	self.x=0

    def inc_x(self):
    	self.x=self.x+1


##############################################################################
# Example 1 - All worked as expected
##############################################################################
#
# f=Foo()
# f.helloworld()
# f.bye_world()
# f.setx(12)
# f.printx()
# f.reset_x()
# f.printx()
# f.inc_x()
# f.printx()
# f.inc_x()
# f.printx()


##############################################################################
# You can't print an object that isn't initiated yet:
##############################################################################
#
# Error: 'Foo' object has no attribute 'x'
##########################################
#
# f=Foo()
# f.printx()

# OK
##########################################
#
f=Foo()
f.reset_x()
f.printx()

Klasses, Init & variabelen

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.

Delete a member - Dictionary

#! /usr/bin/python3
#
##############################################################################

class Foo:
    "Here is an explanation about the foo class"

    def helloworld(self):
    	print ("Hello, world! - Greetings from foo")

    def bye_world(self):
    	print ("Bye, world! - Greetings from foo")

    def setx(self, x):
    	self.x =x

    def printx(self):
    	print (self.x)

    def reset_x(self):
    	self.x=0

    def inc_x(self):
    	self.x=self.x+1


##############################################################################
# Delete a member
##############################################################################
#
# Je kunt een member (=een variabele van een object) verwijderen. Deze code 
# geeft daarom foutmelding AttributeError: 'Foo' object has no attribute 'x'
#
# f=Foo()
# f.reset_x()
# del f.x
# f.printx()

##############################################################################
# Dictionary
##############################################################################
#
f=Foo()
f.reset_x()
f.inc_x()
f.printx()

vars(f)		# Gebeurt nix
#f.vars()	# No such attribute

Ik ben tot hiero gekomen

https://en.wikibooks.org/wiki/Python_Programming/Classes#Dynamic_Class_Structure

Bronnen