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

In [22]:
# Import display
from IPython.display import display

In [30]:
# Example of instantiating a class

# Create a class
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 Add")
        return self.num_1 + self.num_2
    

# Crease an instance of Add
a = Add(10,10)

# Now we can access the function within the class
# using the dot notation
display(x.sum_all())


Method sum_all in class Add
20

Inheritance

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

In [28]:
# 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
display(m.sum_all())

# Call method mult_all
display(m.mult_all())


Method sum_all() in class A:
20
Method mult_all() in class B:
100

Private Members

  • These are created with 2 underscores within a class
  • They can only be accessed outside the class if we add _ClassName

In [38]:
# 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
display(a._A__num_1)
display(a._A__num_2)


5
5

Checking for subclasses

  • issubclass(class_A, class_B)
  • You can use this to determine if one class inherits another class.

In [44]:
# Example of sub-class

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

# Instance derived class Multiply(Add)
m = Multiply(10, 10)

# Check if Multiply inherits Add
display(issubclass(Multiply, Add))

# Check if Add inherits Multiply
display(issubclass(Add, Multiply))

# Check if Add inherits itself
display(issubclass(Add, Add))


True
False
True

Checking if an object is an instance of a class

  • isinstance(object, class)

In [91]:
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

# Instantiate: create object
a = Add(10, 10)

# Check if an object is an instance of a class

display(isinstance(a, Add))


Method sum_all() in class A:
True

Representation

  • repr(object) accesses the repr method in a class where the object is an instantiation of the class.

In [81]:
class Add:
    def __init__(self, word_1, word_2, word_3):
        self.word_1 = word_1
        self.word_2 = word_2
        self.word_3 = word_3
        
    def __repr__(self):
        print("Method sum_all() in class A:")
        return self.word_1 + self.word_2 + self.word_3


# Create Add instance
a = Add("I", " Love", " you")
print(a)

# Access _repr_ from Add class
print(repr(a))


Method sum_all() in class A:
I Love you
Method sum_all() in class A:
I Love you

Call class directly with Classmethod

  • @classmethod
  • We can call with a static or instance method

In [93]:
class Add:
    @classmethod
    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

# Static method
display(Add(10,10).sum_all())

# Instance method
a = Add(10, 10)
display(a.sum_all())


Method sum_all() in class A:
20
Method sum_all() in class A:
20

Property

  • property(get_func, set_func)
  • This allows you to get and set a value.

In [95]:
class Car:
    def get_func(self):
        return self._word
    def set_func(self, value):
        self._word = value.upper()
    
    word = property(get_func, set_func)

# Create instance
c = Car()

# Set word property
c.word = "BMW"

# Get name property
display(c.word)


'BMW'

Super

  • super().parent_method()
  • This allows us to call a method from the parent class with the same method name

In [133]:
class A:
    def letter(self):
        print("A")

class B(A):
    def letter(self):
        print("B")
        # Call name method from parent class.
        super().letter()

# Create Circle and call name.
b = B()
b.letter()


B
A

Hash

  • Comparing objects using hash is fast.

In [144]:
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
    
    def __hash__(self):
        return int(self.num_1)

a = Add(10 , 10)
display(hash(a))


10