python creates a class using the metaclass type

  • 2021-12-11 08:32:52
  • OfStack

Directory 1, type Dynamically Creating Classes 1.1 Syntax Format 1.2 Case 1: Creating Classes with type 1.3 Case 2: Creating Classes with Attributes (Methods) with type 1.4 Case 3: Creating a Class Dynamically Inheriting a Specified Class with type

Foreword:

Usually we create classes using class Class name, but have your friends ever wondered who created the class? python It is often said that everything is an object, and an object is created by a class. That class itself can also be regarded as an object, and a class can be made of a metaclass type Create

1. type dynamically creates classes

1.1 Syntax Format

type (Class name, tuple of parent class name (can be empty), dictionary containing attributes (name and value))

1.2 Case 1: Creating a Class Using type


Person = type("Person", (), {})
p = Person()
print(type(p))
print(Person.__name__)

Results:


<class '__main__.Person'>
Person


Note: Person in type ("Person", (), {}) can be written as any other string, but when you print the name of the class, it will become that you write other strings


Person = type("Per", (), {})
p = Person()
print(Person.__name__)

Results:

Per

Therefore, in order to make the program code more friendly, 1 general variable names and set class names remain the same 1

1.3 Case 2: Creating a Class with Attributes (Methods) Using type


def show(self):
    print(" Show yourself ")
Person = type("Person", (), {"age": 18, "name": "jkc", "show": show})
p = Person()
print(p.age)
print(p.name)
p.show()

Results:

18
jkc
Show yourself

We dynamically created a parent class for Object The attributes are age , name The method is show Class of

1.4 Case 3: Using type to dynamically create a class that inherits the specified class


class Animal:
    def __init__(self, color="blue"):
        self.color = color

    def eat(self):
        print(" Eat ")
Dog = type("Dog", (Animal, ), {})
dog = Dog()
dog.eat()
print(dog.color)

Results:

Eat
blue

We dynamically created an inheritance Animal Class Dog Class, you can use the Animal All methods and properties of the class


Related articles: