class Base(object):
name = "yao"
age = 23
def setUp(self):
if hasattr(self, "name"):
print "setUp, %s" % getattr(self, "name")
from new import classobj
myClass= classobj("HelloClass", (Base, ), {"***":"boy", "school":"hn"})
myobject = myClass()
myobject.setUp()
print myobject.*** + " ->" + str(myobject.age)
# >>>
print getattr(myobject, "school")
def initParent():
globals()['MyChildClass']=type("MyChildClass", (Base, ), {"***":"girl",
"school":"nn"})
initParent()
myobject = MyChildClass()
myobject.newAttr = "hello" #动态创建属性
print myobject.***, myobject.school
print getattr(myobject, "newAttr")
class A(MyChildClass): #MyChildClass就是动态创建的类。
def testup(self):
if hasattr(self, "***"):
print " have *** attritue, %s" % getattr(self, "***")
if hasattr(self, "newAttr"): #这样的属性就没有了
print "HAVEing!"
a = A()
a.testup()
Python动态创建类
最新推荐文章于 2023-07-31 16:57:05 发布