Tag: Programming

Python – Metaclass

In Python, metclass is a class whose instances are classes. Metaclass are derived from type.

Metaclasses change the classes automatically when decorators are not efficient use metaclass.

Metaclass implements __new__ method which calls the parent class to create a new instance. The creation of metaclass includes the name of the class, class bases and attributes used in the class.

Metaclass are used to create class dyunamically using the type keyword. See following code snippet-

car = type("vehicle", "Vehicle", "{speed:50}")

Here the type accepts the name of the instance, then the baseclass name and attributes defined for the object.

See the below code to create your own metaclass.

Vehicle_Meta class inherits from type. Implements __new__ method which accepts four parameters. cls, name – name of the class to be dynamically created, bases – meta class base class and dict- attributes attached to the class. custom attribute speed is created.

Vehicle class refers to the meta class Vehicle_Meta.

When the __dict__ is accessed it has the custom attribute along with other attributes created as a part of Class.

Shallow and Deep Copy in Python

Shallow Copy

Shallow copy in Python allows to create copy of objects. With shallow copy the object references to the same memory and shares the value across the objects.

See example below different ways to shallow copy objects.

Assign object to other object with “=” operator.

Performance: this approach is fastest as comapred to [:] and deep copy

Assign object to other object with [:]. This creates a new reference to the memory allocated for the list.

Performance: this approach is slower than the “=” operator as it creates a new reference.

Deep Copy

Deep copy creates a new instance of the object and allocates different memory location and the values associated are different from the copied/source object.

Below example uses deepcopy() method from the copy package.

Performance: This approach has a comprehensive operation and slower the above 2 approaches.

Deep copy wont call the constructor and copies the data with the new memory chunk.

Property getter, setter and deleter in Python

Python uses getter, setter and deleter to the method to the attrinutye which is decorated as @property

Python allows to control the access of attribute using @property keyword. This is also called as attribute encapsulation.

Attribute that is decorated as @proptery uses a method name same as encapsulated atribute.

This methods are called atutomatically when the objects are trying to access or set value to such encapsulated attribute.

When a value is set to the property, attribute setter ios called.

When attribute is deleted using del, deleter is called.

Here the __empname is hidden to the objects and can be accessed using getter method. This shows the encapsulation concept of object oriented programming with Python.

Python- Abstract Class and Method

Abstract class are a blueprint for other classes and is considered as the class designer.

A class whn designed needs a concrete implementation. Abstract class hold a contract between a designer and the implementer.

Instance of Abstract class cannot be created and it needs to be inherited and implemented in the subclass.

For a larger functional unit or a generic/common functionlaity is to be provided use Abstract class. Abstract class allows to implement the fucntionlaity in the subclass.

Abstract method allows to declare the method and impelement the functionality in the subclasses where the Abstract class is inherited.

A method in class can be decorated/marked as abstract with @abstractmethod keyword. Use Import abc to use the Abstract method.

See below example of using Abstract method-

Here abc is imported and the print_output method is decorated as @abstractmethod. The definition of such method is pass which means a control is passed to the subclasses where a implementation is expected for printing based on the output device.

The print_out method is implemented in Printer and Console subclasses inherited from class having a abstract method.


Python raises a TypeError if we try to instantitate a Abstract Class.

TypeError: Can’t instantiate abstract class OutputDevice with abstract method print_output

Python also raises error if the subclass doesn’t implement the abstract method in suclass.

See the below example for TypeErrors whilst using Abstract Class

Here the Log class does not implement the print_output abstract method.

You can also see the various usage of Static Methods, ClassMethods and there difference’s.

Python- Static Methods

Static Methods can be used when Class object is not required to call a method but the method’s within that class are related to execute the code.

Also static methods can be used when the state of the object is not required to maintain. i.e. they don’t have the ability to change the state of the object

Decorate class method with @staticmethod keyword to make the method static.

See below example of using Static Method-

validate_instance_counter(param) method is marked as static method.

Python- Decorator Stacking

Python allows to apply multiple decorators to callable object.

The decorator function is called based on the order or the sequence it has been listed.

Decorator can also use there own arguments. In the below example @log decorator a parameter is passed with value ‘log sample’.

Log decorator has 2 wrapper functions. Outer function accepts the reference or pointer to the decorated fucntion and an internal function holds arguments that are passed to the decorated fucntion.

The decorated function is called from the internal wrapper function along with the parameters.

The parameter passed to the decorator is also assessible in the decorator function.

Coming back to Decorator stacking. The below example is used to decorate the fucntion with multiple decorators. Here log and executiontime are decorator function and stacked on the decorated function i.e. sample

Python – Method Resolution Order

Multiple inheritnace is possible in Python but it comes with the Diamond Problem as seen in the diagram below.

Class A is super class of Class B and Class C

Class D is sub-class of Class B and Class C

When instance of Class D is created which Class method will be called? This is a Diamond Problem

MRO will in this case execute the method of the Class B. i.e. in multiple inheritance the method of first in the super class is executed from left to right. If that method does not exists in first super class then will try and check in the second and finally to the parent class.

Use info() method to know which super class method will be executed. See below code snippet

But there are issues with MRO too. If the Class D inherits Class A and Class C it throws error – Cannot create a consistent MRO. See below code.