type 创建类,赋予类静态方法等

类方法
class ObjectCreator(object):
    pass

@classmethod
def testClass(cls):
    cls.temp = 666
    print(cls.temp)

test = type("Test",(ObjectCreator,),{'testClass':testClass})
t = test()
t.testClass()#字典中的键

静态方法
class Test:
    pass
@staticmethod
def TestStatic():
    print("我是静态方法----------")

t = type('Test_two',(Test,),{"TestStatic":TestStatic})
print(type(t))
print(t.TestStatic)
print(t.TestStatic())

class Test:
    pass
def Method():
    return "定义了一个方法"
test2 = type("Test2",(Test,),{'Method':Method})
# 第一个参数为类名,第二个参数为父类(必须是元组类型),
# 第三个参数为类属性,不是实例属性
# print(type(test2))
# print(test2.Method())
print(hasattr(test2,'Method'))
# hasattr查看test2是否包含有Method方法

2020-05-08

原文地址:https://www.cnblogs.com/hany-postq473111315/p/12846940.html