创建类方式
#创建类:方式1
class Foo(object):
v1 = 123
def func(self):
return 999
#创建类:方式2
Foo = type("Foo", (object,), {"v1":123, "func": lambda self: 999}
obj = Foo()
print(obj.v1)
print(obj.func())
type解释
Python的最终父类是object,实际object是由type创建的 ; type创建类
也就可以在__new__方法里操作Foo里的类变量 如v1 del attrs["v1"] 对变量操作或者修改
class MyType(type):
def __new__(cls, name, bases, attrs):
print(name, bases, attrs)
xx = super().__new__(cls, name, bases, attrs)
return xx
# Foo = type("Foo", (object,), {"v1":123, "func": lambda self: 999}
class Foo(object, metaclass=MyType):
v1 = 123
def func(self):
pass
D:\python\system\dahe\venv\Scripts\python.exe D:/python/system/dahe/TestDemo.py
Foo (<class 'object'>,) {'__module__': '__main__', '__qualname__': 'Foo', 'v1': 123, 'func': <function Foo.func at 0x0000024C79B949A0>}
Process finished with exit code 0