1 def demo(obj): 2 print('===================') 3 obj.x = 1 4 obj.y = 2 5 obj.z = 3 6 return obj 7 8 @demo 9 class Foo: 10 pass 11 12 f1 = Foo() 13 print(Foo.__dict__) 14 输出: 15 =================== 16 {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 'x': 1, 'y': 2, 'z': 3}
一切皆对象,函数和类都是对象 例如:
1 def demo(obj): 2 print('===================') 3 obj.x = 1 4 obj.y = 2 5 obj.z = 3 6 return obj 7 @demo 8 def test(): 9 print('这是个测试函数') 10 test() 11 print(test.__dict__) 12 输出: 13 =================== 14 这是个测试函数 15 {'x': 1, 'y': 2, 'z': 3}
1 def test(**kwargs): 2 def wrapper(obj): 3 for key, val in kwargs.items(): 4 setattr(obj, key, val) 5 return obj 6 7 return wrapper 8 9 10 @test(a=1, b=2) # @wrapper 11 class Foo: 12 def __init__(self, name): 13 self.name = name 14 15 16 print(Foo.__dict__) 17 输出: 18 {'__module__': '__main__', '__init__': <function Foo.__init__ at 0x00000000024C3280>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 'a': 1, 'b': 2}