Learning Python

18. Classes

18.1. Creating a class and object

class MyClass:
    a = 42

def main():
    myobject = MyClass()
    print(myboject.a)

18.2. The constructor method

During the instantiation of a class the constructor method is called to initialize the object. In Python the method name __init__ is reserved for this purpose.

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

person1 = Person("John", 42)

print(person1.name)
print(person1.age)

18.3. Define an object method

Object methods are functions that belong to the object and operation withing the context of the current object.

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

    def myfunc(self):
        print("My name is " + self.name)

person1 = Person("John", 42)
person1.myfunc()

18.4. The self parameter

The self parameter is a reference to the current instance of the class and has been specified in PEP-8, but isn’t a reserved keyword. The name of first argument can be anything you want.

class Person:
    def __init__(abc, name, age):
        abc.name = name
        abc.age = age

    def myfunc(xyz):
        print("My name is " + xyz.name)

person1 = Person("John", 42)
person1.myfunc()

18.5. Object actions

Modify an object property

person1.age = 40

Delete an object property

del person1.age

Delete an object

del person1

18.6. Inheritance

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

    def myfunc(self):
        print("My name is " + self.name)

class Engineer(Person):
    pass

engineer1 = Engineer("John", 42)
engineer1.myfunc()
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def myfunc(self):
        print("My name is " + self.name)

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

engineer1 = Engineer("John", 42, "Electronics")
engineer1.myfunc()
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def myfunc(self):
        print("My name is " + self.name)

class Engineer(Person):
    def __init__(self, name, age, field):
        super().__init__(name, age)
        self.field = field

engineer1 = Engineer("John", 42, "Electronics")
engineer1.myfunc()