Python Classes

A class has many functions.

Creating a class : __init__

  • The init method is also called a constructor.
  • It takes in parameters and assigns fields to the new instance.
  • The __init__ method gets called when memory for the object is allocated.
  • class Point: def __init__(self, x, y): _x = x _y = y
  • Your x and y parameters would be stored in variables on the stack and would be discarded when the init method goes out of scope. Setting those variables as self._x and self._y sets those variables as members of the Point object (accessible for the lifetime of the object).
  • Thanks to StackOverflow, here’s an awesome example to understand the difference between a variable declared inside a class, and a variable declared inside an __init__ function:
  • class MyClass(object): i = 123 def __init__(self): self.i = 345 a = MyClass() print a.i 345 print MyClass.i 123

Inheritance:

We can have a class inheriting from other classes. Specify the inheritance in paranthesis.

# Example of inheritance 
class Add:
def __init__(self, num_1, num_2):
self.num_1 = num_1
self.num_2 = num_2
    def sum_all(self):
print("Method sum_all() in class A:")
return self.num_1 + self.num_2
class Multiply(Add):
def mult_all(self):
print("Method mult_all() in class B:")
return self.num_1 * self.num_2
# Instantiate Multiply class
m = Multiply(10, 10)
# Call method sum_all
# This is inherited from class Add
print m.sum_all()
20
# Call method mult_all
print m.mult_all()
100

Private Members

Within a class, Private Members are created with two underscores. They are accessible only in their own class

# Example of Private Members within a Class
class A:
def __init__(self, num_1, num_2):
self.__num_1 = num_1
self.__num_2 = num_2
    __num_1 = 10
__num_2 = 10
# Instantiate class
a = A(5, 5)

# Call private member
print a._A__num_1
5
print a._A__num_2
5

Super

  • This allows us to call a method from the parent class with the same method name
  • super().parent_method()
class A:
def letter(self):
print("Hi there!")
class B(A):
def something(self):
print("Morning!")
# Call name method from parent class.
super().letter()
b = B()
b.letter()
Morning!
Hi there!

Alright that’s it for now! Thank you for spending your time. Cheers!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.