动态属性和对象
In [39]:
class Print(object):
class_name = 'print'
def __init__(self):
self.object_name='object'
def do_foo(self):
print 'foo'
def do_bar(self):
return 'bar'
def do_two(self, value):
print value
@property
def names(self):
return self.object_name
@classmethod
def class_bar(cls):
print 'class_bar'
@staticmethod
def static_foo():
print 'static_foo'
In [40]:
print getattr(Print, 'class_name')
In [41]:
obj = Print()
print getattr(obj, 'object_name')
In [21]:
# if the attribute does not exist
print getattr(obj, 'my_name')
In [42]:
# if not exist, give a default value
print getattr(obj, 'my_name', 'default_value')
In [43]:
getattr(obj, 'do_foo')()
In [44]:
print getattr(obj, 'do_bar')()
In [45]:
getattr(obj, 'do_two')('gaufung')
In [46]:
getattr(obj, 'names')
Out[46]:
In [16]:
getattr(obj, 'class_bar')()
In [17]:
getattr(obj, 'static_foo')()
In [28]:
hasattr(obj, 'do_bar')
Out[28]:
In [29]:
hasattr(obj, 'gaofeng')
Out[29]:
In [33]:
setattr(obj, 'name', 'gaufung')
print hasattr(obj, 'name')
print getattr(obj, 'name')
In [34]:
def add(x, y):
return x+y
setattr(obj, 'add', add)
print getattr(obj, 'add')(2,1)
In [36]:
print hasattr(obj, 'add')
In [37]:
delattr(obj, 'add')
print hasattr(obj, 'add')
In [38]:
func_name = 'add'
eval(func_name)(1,2)
Out[38]: