Python Basic -playing with classes

Shubham Saket
4 min readApr 11, 2021

Code effortlessly

A python class gives us structure for creating a new entity in python with methods associated with it.

Default data types in python such string, list etc. all are classes (check builtins.py).

Let us look go through some examples to clear our understanding:

  1. Creating a class
class A:
age = 4

def get_age(self):
print(A.age)

In the above example we have defined a class A and associated variable ‘age’ and method ‘get_age’ to it. Notice inside get_age method we are calling value of age as A.age which is because of the scope of variable.

# Create an instance of class A
a = A()

# calling age variable and get_age method
print(a.age)
a.get_age()

‘a’ is an instance of a class A. For calling a class’s method we need to initiate an instance of the class and then call the method. We can create more than one instance of a class at time. Also we can create class which restricts more than one instance of itself.

class B:

__instance = None

def __init__(self):
if B.__instance is not None:
raise Exception("""This class is a singleton cannot create more than one instance!""")
else:
B.__instance = self

@staticmethod
def getInstance():
if B.__instance is None:
B()
return B.__instance
instance_1 = B()
instance_2 = B()

Static methods, much like class methods, are methods that are bound to a class rather than its object. We can call a static method without initiating a class. We can call the static method getInstance() to avoid this error as it will check if an instance of class B exists or not. If yes, it will return same instance and if not, it will create a new instance of the class.

instance_1 = B.getInstance()
instance_2 = B.getInstance()

print(instance_1)
print(instance_2)

2. Inheritance:

class ParentClass:
def __init__(self,name,number):
self.name = name
self.x = number
def print_square(self):
print(self.x**2)

def print_name(self):
print(self.name)

class ChildClass(ParentClass): # inheriting ParentClass
def __init__(self, name, number):
super().__init__(name,number) #instantiating ParentClass

def print_cube(self):
print(self.x ** 3)


p = ChildClass('john',3)
p.print_cube()
p.print_name()
p.print_square()

ChildClass inheriting ParentClass implies ChildClass will acquire all the attributes of the ParentClass. We can see in the above example that instance p can can use print_square method which is defined in ParentClass only. super().__init__() is used to instantiate ParentClass.

3. Over riding of methods by child class:

When a class inherits as parent class it may happen that name of a method in parent is same as the name of a method in child class. In such cases the method of child class overrides the parent method.

Let us see an example:

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

def say_hello(self):
print("Hello Mr. {}".format(self.name))


class german_man(hello_man):
def __init__(self,name):
super().__init__(name)

def say_hello(self):
print("Hallo Herr {}".format(self.name))

h = hello_man('stark').say_hello()
g = german_man('stark').say_hello()

4. Multiple inheritance:

A class can inherit attributes from more than one class.

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

def say_hello(self):
print("Hello Mr. {}".format(self.name))

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

def ask(self,):
print("How are you {}".format(self.name))


class hallo_herr(hello_man,ask_how):
def __init__(self,name):
super().__init__(name)

def say_hello(self):
print("Hallo Herr {}".format(self.name))

h = hello_man('stark').say_hello()
g = hallo_herr('stark').ask()

Note: In case of multiple inheritance if there is a method in more than one parent classes the method definition will be taken from class inherited first.

I hope this post helped you in learning basic concept of python ‘class’.

That’s all pythoners.

--

--