Python元类与枚举类
一、元类
1、type()函数可以返回对象的类型,也可以创建出新的类型。它可以改变类创建时的行为,实现动态创建类。
# 第一个参数:类名 # 第二个参数:父类元祖 # 第三个参数:属性、方法 A = type("A",(object,),{"name":"zhou"}) a = A() print(type(A)) # <class 'type'> print(type(a)) # <class '__main__.A'> print(a.name) # zhou
2、可以通过metaclass指定类的元类
class MyType(type): pass class A(metaclass=MyType): pass print(type(A)) # <class '__main__.MyType'>
另一种指定函数元类(转载):
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
二、枚举类
在开发中经常设置多组常量,Enum可以把一组相关常量定义在一个class中,且class不可变,而且成员可以直接比较。
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开始计数。
也可以通过继承Enum类来自定义:
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
相关推荐
ericasadun 2020-06-03
luckymaoyy 2020-05-09
cnflat0 2020-01-23
Joymine 2020-01-13
狼窝 2019-12-15
jianghuchuanke 2019-11-19
NoBlueSky 2019-11-17
iconhot 2019-11-09
xzxkag 2019-11-04
taizuduojie 2019-11-03
liangds 2019-08-02
paopao00 2019-06-29
AquariusYuxin 2019-06-27
QiaoranC 2019-06-27
89570691 2014-05-06
hhboyggyy 2010-04-26