Examples of Python Classes

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

This tutorial is part of the Python tutorial for PHP developers.  So some programming knowledge is assumed.

We start with a Python class example based from A Byte of Python

class Person:
    def __init__(self, name):
        self.name = name

    def sayHi(self):
        print('Hello, my name is', self.name)

p = Person('John')
p.sayHi()

This is a class named Person with an initializer (the __init__ method) and a method called sayHi().  When a function is a part of a class, they are called methods.

Python __init__ initializer

The __init__ method is called when we instantiate the “p” object.  “p” is an object instance of the class Person.  In the statement p.sayHi(), the object instance p is implicitly passed into the sayHi method as the first “self” argument.  Every method has self as a first argument so that methods can store and access the object properties. See how the initializer sets the name property of the object with self.name.  See how the sayHi() method accessed the “name” property of the object with self.name.

Python does not have private or protected properties.  By convention a property is named with a leading underscore to indicate that it should be used only internally within the object.

Here is a class that has properties that can be set during object instantiation …

class Animal: 
    def __init__(self, **kwargs):
        self.properties = kwargs;

    def set_property(self, key, value):
        self.properties[key] = value

    def get_property(self, key):
        return self.properties.get(key, None)

a = Animal(color = "brown")
a.set_property("feet", 2)
print(a.get_property("color"))
print(a.get_property("feet"))

It demonstrates the use of keyword named arguments (**kwargs) in the initializer.  These arguments are saved to self.properties and retrieved using get_property method.  When getting a non-existing property, None is returned.

See how color brown is set in the initializer and 2 for feet is set using the set_property.

It may seem that __init__ is a constructor, but it is really just an initializer.  A real constructor is __new__.

Python decorators

Decorators are used to create accesser and setter methods like so…

    @property
    def color(self):
        return self.properties.get('color', None)

    @color.setter
    def color(self, myColor):
        self.properties['color'] = myColor

    @color.deleter
    def color(self):
        del self.properties['color']

And now color can be set and get by …

a.color = ‘white’

print(a.color)

Python __iter__ method

You can also have an __iter__ method in your class to make the class iterable by using “yield” within the __iter__.  yield is like return, except that the method picks up from the yield the next time it is called.

Python Class Inheritance

Another class can inherit from Animal by …

class Dog(Animal):

A child class can call the method of its base class by using super().