Home >Backend Development >Python Tutorial >Introduction to metaclasses and enumeration classes in Python (code examples)
This article brings you an introduction to metaclasses and enumeration classes in Python (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Metaclass
1. The type() function can return the type of the object or create a new type. It can change the behavior when a class is created and realize dynamic creation of classes.
# 第一个参数:类名 # 第二个参数:父类元祖 # 第三个参数:属性、方法 A = type("A",(object,),{"name":"zhou"}) a = A() print(type(A)) # <class 'type'> print(type(a)) # <class '__main__.A'> print(a.name) # zhou
2. You can specify the metaclass of the class through metaclass
class MyType(type): pass class A(metaclass=MyType): pass print(type(A)) # <class '__main__.MyType'>
Another designated function metaclass (reproduced):
def upper_attr(future_class_name, future_class_parents, future_class_attr): attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__')) uppercase_attr = dict((name.upper(), value) for name, value in attrs) return type(future_class_name, future_class_parents, uppercase_attr) class Foo(metaclass = upper_attr): # 指定元类 bar = 'bip' print(hasattr(Foo, 'bar')) # 输出: False print(hasattr(Foo, 'BAR')) # 输出:True
2. Enumeration class
In development, multiple sets of constants are often set. Enum can define a set of related constants in a class, and the class is immutable, and the members can be directly compared.
from enum import Enum pay_methods = Enum("PayMethods",("CASH","WEIXIN","ALIPAY","UNIONPAY",)) for name, member in pay_methods.__members__.items(): print(name, ',', member, ',', member.value) # CASH , PayMethods.CASH , 1 # WEIXIN , PayMethods.WEIXIN , 2 # ALIPAY , PayMethods.ALIPAY , 3 # UNIONPAY , PayMethods.UNIONPAY , 4 # value属性则是自动赋给成员的int常量,默认从1开始计数。
You can also customize it by inheriting the Enum class:
from enum import Enum, unique @unique # 帮助我们检查是否重复 class PayMethods(Enum): CASH = 0 # 设置CASH.value = 0 WEIXIN = 1 ALIPAY = 2 UNIONPAY = 3 print(PayMethods['CASH']) # PayMethods.CASH print(PayMethods(1)) # PayMethods.WEIXIN print(PayMethods.ALIPAY.value) # 2
The above is the detailed content of Introduction to metaclasses and enumeration classes in Python (code examples). For more information, please follow other related articles on the PHP Chinese website!