import inspect,sys def get__function_name(): #獲取正在運行函數(或方法)名稱
return inspect.stack()[1][3] def shuzf(): print(sys._getframe().f_code.co_name) print(get__function_name())
def __init__(self,name,age): self.name = name self.age = age Dog_class = type("Dog",(object,),{"role":"dog","__init__":__init__}) #動態添加屬性與方法
d = Dog_class('shuzf',22) print(type(Dog_class)) print(type(d)) print(d.role,d.name,d.age) out: <class 'type'> <class '__main__.Dog'> dog shuzf 22
class A(): name = 'python' @classmethod def funcmethod(cls): return 'Hello world:funcmethod' setattr(A, 'age',30) #建立變量並賦值,可在下次直接使用
setattr(A,'funcmethod_class',A.funcmethod) #建立變量並賦值方法