First of all we need to be clear: in python, everything is an object
class Student:
pass
zhangsan = Student()
What are the characteristics of the object:
1. Can be cited
a = zhangsan
2. Can be entered as a function parameter
func(zhangsan)
3. Can be used as the return value of a function
def func():
return zhangsan
4. Can be used as a container element
lis = ["hello, world", 1, zhangsan]
And the classes we define also use these features, so we can replace the above zhangsan with Student, and draw the conclusion:
Classes are objects too! ! !
Since a class is an object, it must be instantiated by a class, and this class is the metaclass
a = 5
print(type(a))
get a is of type int
print(type(type(a)))
Get the type type, that is, the class of int is the type class, and this type is the metaclass we are looking for!
The class of a class is a metaclass, the type class
Now that we know that classes are also instantiated through metaclasses, can we also create classes through metaclasses in the future?
of course can
Method 1: Create a class directly
class People: country = "China" def __init__(self, name, age): self.name = name self.age = age def tell_info(self): print(f"{self.name} is from {self.country}, and he is {self.age} years old") chen = People("chenjun", 21) chen.tell_info()
Method 2: Create a class through a metaclass
First, we need the three elements that make up the class as parameters of the metaclass
Parameter 1: class name, such as People above
Parameter 2: The base class (parent class) of the class, in python3, if the inherited class is not specified, the object class is inherited by default
Parameter 3: Namespace
Then the definition code is as follows:
class_name = "People" class_bases = (object,) class_dic = {} class_body = """ country = "China" def __init__(self, name, age): self.name = name self.age = age def tell_info(self): print(f"{self.name} is from {self.country}, and he is {self.age} years old") """ exec(class_body, globals(), class_dic) People = type(class_name, class_bases, class_dic) chen = People("chenjun", 21) chen.tell_info()