Create Classes Dynamically in Python
A class is defined as a storage of variables of an instance, and a class is a method that is used to specify an object type. A class can be used to make as many instances of objects of the type of object that are needed. An object is an identified entity with some attributes that are also called data members and behaviours, also called member functions. A group of objects that share similar characteristics and behaviour is an instance of the same class. A class is a prototype that is user-defined, and with the help of classes, objects are created. A new type of object is created by creating a new class that allows instances of that type to be made. Each class can have attributes attached to it to maintain its state. Consider an example: you want to keep the number of dogs that may contain different attributes like Breed and age. If we use a list to track the number of dogs, then the first element could be a dog's Breed, and the second element could be the age. But what if there are 100 different dogs? Then how do we know which element is supposed to be which? What, do you want to add other properties to these dogs? This lacks organization, and it's the exact need for classes.
Syntax for defining a class:
class ClassName:
#statement
class is a keyword in Python that is used to define the class.
Syntax for defining an object:
Obj = ClassName()
print(obj.atrr)
The class can be called the user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance.
Some Key Points on Python Class:
- Classes are declared by class keyword.
- The variables that belong to the class are called attributes.
- Attributes are always public and can be accessed with the help of a dot (.)
Creating a Class in Python:
Code:
class Dog:
sound = "bark"
The class is created with the help of the class keyword, and the name of the class is a dog.
The Object of the Python Class:
An object is an instance of class. A class is like a blueprint, while an object is an instance that is a copy of the class with original values.
An object contains:
- State: The attribute of an object that also shows the properties of an object.
- Behaviour: The method of an object that also shows the response of an object to other objects.
- Identity: It gives a distinct name to an object and enables one object to interact with other objects.
Declaring Class Objects (Also called Instantiating a Class):
When an object in a class is created, the class is referred to as instantiated. All the instances share the attributes and the behaviour of the class. However, the values of the attributes are distinct from each other. A single class may contain many instances.
Example of Python Class and object:
To create an object in Python, we have to first create a class and instantiate a class to create a new instance for the class that we create. This process is called as object instantiation.
Code:
# Python3 program to demonstrate instantiating a class
class Dog:
# A simple class attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code Object instantiation
bull_dog = Dog()
# Accessing class attributes and methods through objects
print(bull_dog.attr1)
bull_dog.fun()
Output:
mammal
I'm a mammal.
I'm a dog.
Explanation:
In the class Dog, we create an object that is basically a Dog named bull_dog. This class has only two class attributes, saying that bull_dog is a dog and a mammal. We have two class variables, attr1 and attr2. A method is created with the name fun () that returns the string "I'm a, {attr1}" and "I'm a, {attr2}". An object of the dog class is created and printed the attr1 of the object, and in the end, the fun () function is called.
Self Parameter:
A method is called of the object as my object.method (arg1, arg2), which is automatically converted by Python into MyClass.method (myobject, arg1, arg2).
Code:
class Python:
def __init__(self, name, company):
self.name = name
self.company = company
def show(self):
print("Hello my name is " + self.name+" and I" +
" work in "+self.company+".")
obj = Python ("John", "Dev")
obj.show()
Output:
Hello, my name is John, and I work in Dev.
The parameter self in the init function is not called itself; instead of it, you can use any other name.
Code:
class A:
def __init__(somename, name, company):
somename.name = name
somename.company = company
def show(somename):
print("Hello my name is " + somename.name + " and I work in "+somename.company+".")
obj = A("John", "Google")
obj.show()
Output:
Hello my name is John and I work in Google.
Explanation:
In the code, a class A is created with name and company as instance variables in the constructor. A method show is created which outputs the string "Hello my name is" + {name} +" and I work in “ + {company}+”.”. A person class object is created with the name John and company Google to the instance variable.
Pass Statement:
When using a pass statement in the class, it does not give the output of the class in action. It merely allows the program to skip that section of the code without doing anything. It is frequently implemented when the syntactic constraints of Python want a statement that is valid, but there is no use of code that must be executed.
Syntax:
class MyClass:
pass
__init__() method:
The __init__() in class is the same as constructors in C++ and Java. The constructors are used for initializing the object's state. Like methods, a constructor also consists se of statements executed at the time of the creation of the object. This method is run on its own. This method is useful for any initialization you want to do with your object.
Example of __init__() method:
Code:
# Sample class with the init method
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Ram')
p.say_hi()
Output:
Hello, my name is Ram
Explanation:
In the example, a Person class is created, and a name variable is created in the constructor. A method is created, say_hi(), which results in the output of a string "Hello, my name is {name}". An object of the Person class is created, and the name Ram is passed to the instance variable. Finally, the say_hi() method is called for the class.
__str__() method:
The __str__() method defines how a class's object should be represented as a string. It is often used to give an object a textual representation that is human-readable and is helpful for logging, debugging, or showing users object information. The __str__() method is automatically used when a string object is created using the built-in functions print() and str(). Let’s see an example of __str__() method:
Code:
class MyClass:
def __init__(self, name, company):
self.name = name
self.company = company
def __str__(self):
return f"My name is {self.name} and I work in {self.company}."
my_obj = MyClass("John", "Google")
print(my_obj)
Output:
My name is John, and I work for Google.
Explanation:
In the above code, MyClass is created with two instance variables: name and company. The instance variable name and company are returned in the __str__() method. Finally, the object of MyClass is created, and the object is printed, and the __str__() method is called.
Class and Instance Variables:
Instance variables are used for data that are unique to each instance, and for attributes and methods, class variables that are shared by all instances of the class are used. Variables whose values are assigned inside the constructor are called instance variables, while variables whose value is assigned in the class are called class variables.
Example of defining an instance variable with the help of a constructor.
Code:
class Dog:
animal = 'dog'
def __init__(self, breed, color):
self.breed = breed
self.color = color
Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")
print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger. Breed)
print('Color: ', Rodger.color)
print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)
print("\nAccessing class variable using class name")
print(Dog.animal)
Output:
Rodger details:
Rodger is a dog
Breed: Pug
Color: Brown
Buzo details:
Buzo is a dog
Breed: Bulldog
Color: Black
Accessing class variable using class name
dog
Explanation:
In the above code Dog class is defined with animal as class variable to the string "dog". This animal class variable is shared by all the objects of a class and can be accessed using the class name. There are two instance variables: Breed and colour. There are two objects of the Dog class are created, and both objects are printed with the class variable named animal.
Let’s define an instance variable with the normal method:
Code:
class Dog:
animal = 'dog'
def __init__(self, breed):
self.breed = breed
def setColor(self, color):
self.color = color
def getColor(self):
return self.color
Rodger = Dog("pug")
Rodger.setColor("brown")
print(Rodger.getColor())
Output:
brown
Explanation:
In the given example, a dog class is defined as a class variable created as an animal. An instance variable, Breed, is created in the constructor. The Dog class contains two methods named setColor and getColor, which are used to create and initialize an instance variable and retrieve the value of the instance variable. An object of the Dog class is made with the instance variable brown, which is set and prints the value of this.
Creating Classes Dynamically in Python:
We have seen what are classes and objects and how to create classes and objects in the class. So, basically, a class is said to be a collection of instance variables and methods to specify a type of object. There are a lot of significant advantages of Python over statically typed languages because of its flexibility since Python is a dynamic programming language. The code in Python can be imported dynamically, and classes can be created dynamically at run-time. The type () function in Python is used to create classes in Python dynamically.
Syntax of type function:
type()
The syntax of type gives the output as the type of object:
Example of type function:
print(type("Python Programming !"))
print(type(17062))
Output:
<class 'str'>
<class 'int'>
Creating Dynamic Classes in Python:
The following syntax tells how classes can be created dynamically in Python
type(name, bases, attributes)
Parameters:
name: The name of the class that is defined by the user
bases: A list of base classes, and its type is tuple
attributes: the data members and methods contained in the class
Let’s see an example of the new type of object:
Code:
def constructor(self, arg):
self.constructor_arg = arg
def displayMethod(self, arg):
print(arg)
@classmethod
def classMethod(cls, arg):
print(arg)
dynamic_class = type("Dynamic", (object, ), {
# constructor
"__init__": constructor,
# data members
"string_attribute": "Python Programming !",
"int_attribute": 1706256,
# member functions
"func_arg": displayMethod,
"class_func": classMethod
})
# creating objects
obj = dynamic_class("constructor argument")
print(obj.constructor_arg)
print(obj.string_attribute)
print(obj.int_attribute)
obj.func_arg("Dynamic Class")
dynamic_class.class_func("Class Dynamically Created !")
Output:
constructor argument Python Programming ! 1706256 Dynamic Class Class Dynamically Created !
Explanation:
In the example above, a dynamic class is created named dynamic_class with a constructor. The dynamic_class data members are string_attribute and int_attribute, and the member functions of dynamic_class are displayMethod () and classMethod(). A dynamic_class objected is created, and all the data members are assigned and displayed; all the members of functions of dynamic_class are also called.
Let us consider another example:
Code:
def createClass(classname, attributes):
return type(classname, (object,), {
'__init__': lambda self, arg1, arg2: setattr(self, 'args', (arg1, arg2)),
'args': attributes
})
Car = createClass('Car', {'name':'', 'age':0})
mycar = Car('Audi R8', 3)
print(f"Car name: {mycar.args[0]}\nCar age: {mycar.args[1]} years")
Output:
Car name: Audi R8 Car age: 3 years
Explanation:
The function createClass is defined with class and its attributes, and the return type is object and arguments.