类作为装饰器、元类
一、类作为装饰器
class Test(object):
def __call__(self):
print("test1")
t=Test()
t()
class Test(object):
def __init__(self,func):
print("---初始化---")
print("func name is %s"%func.__name__)
self.__func=func
def __call__(self):
print("---装饰器中的功能---")
self.__func()
@Test # test=Test(test)
def test():
print("---test2---")
def __init__(self,func):
print("---初始化---")
print("func name is %s"%func.__name__)
self.__func=func
def __call__(self):
print("---装饰器中的功能---")
self.__func()
@Test # test=Test(test)
def test():
print("---test2---")
test()
运行结果:
test1
---初始化---
func name is test
---装饰器中的功能---
---test2---
---初始化---
func name is test
---装饰器中的功能---
---test2---
二、元类
1、类也是对象
>>> print ObjectCreator # 你可以打印⼀个类,因为它其实也是⼀个对象 <class '__main__.ObjectCreator'> >>> def echo(o): … print o … >>> echo(ObjectCreator) # 你可以将类做为参数传给函数 <class '__main__.ObjectCreator'> >>> print hasattr(ObjectCreator, 'new_attribute') Fasle >>> ObjectCreator.new_attribute = 'foo' # 你可以为类增加属性 >>> print hasattr(ObjectCreator, 'new_attribute') True >>> print ObjectCreator.new_attribute foo >>> ObjectCreatorMirror = ObjectCreator # 你可以将类赋值给⼀个变量 >>> print ObjectCreatorMirror() <__main__.ObjectCreator object at 0x8997b4c>
2、动态地创建类
类也是对象,可以动态的创建,就像其它的对象一样。可以在函数中创建类,使用class关键字即可。
def choose_class(name): if name == 'foo': class Foo(object): pass return Foo # 返回的是类,不是类的实例 else: class Bar(object): pass return Bar MyClass = choose_class('foo') print(MyClass) # 函数返回的是类,不是类的实例 print(MyClass()) # 你可以通过这个类创建类实例,也就是对象
type(类名,由父类名称组成的元组(针对继承的情况,可以为空),包含属性的字典(名称和值))
#使用type创建类 class Test1: pass Test1() Test2=type("Test2",(),{}) Test2() #使用type创建带有属性的类 class Test3: bar=True Test4=type("Test4",(),{"bar":True}) Test_3=Test3() Test_4=Test4() print(Test_3.bar) print(Test_4.bar) """ class Test3_child(Test3): pass 也可以写成 """ Test3_child=type("Test3_child",(Test3,),{}) Test3_c=Test3_child() print(Test3_c.bar) #使用type创建带有方法的类 def echo_bar(self): print(self.bar) Test5=type("Test5",(Test3,),{"echo_bar":echo_bar}) Test_5=Test5() Test_5.echo_bar() print(hasattr(Test5,"echo_bar"))# 判断Test5中是否有echo_bar这个方法 print(hasattr(Test3,"echo_bar")) print(hasattr(Test5,"bar"))# 判断Test5中是否有bar这个方法 print(hasattr(Test3,"bar")) #添加静态方法 @staticmethod def statictest(): print("这是一个静态方法") Test6=type("Test6",(Test3,),{"echo_bar":echo_bar,"statictest":statictest}) Test_6=Test6() Test_6.echo_bar() Test_6.statictest()
自定义元类
def upper_attr(future_class_name,future_class_parents,future_class_attr): newAttr = {} for name,value in future_class_attr.items(): if not name.startswith("__"): newAttr[name.upper()]=value return type(future_class_name,future_class_parents,newAttr) class Foo(object,metaclass=upper_attr): bar = "bip" print(hasattr(Foo, 'bar')) print(hasattr(Foo, 'BAR')) f=Foo() print(f.BAR)
浙公网安备 33010602011771号