动态属性和对象

1 getattr


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'

1.1class attribute


In [40]:
print getattr(Print, 'class_name')


print

1.2 object attribute


In [41]:
obj = Print()
print getattr(obj, 'object_name')


object

In [21]:
# if the attribute does not exist
print getattr(obj, 'my_name')


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-f82a56842dc1> in <module>()
      1 # if the attribute does not exist
----> 2 print getattr(obj, 'my_name')

AttributeError: 'Print' object has no attribute 'my_name'

In [42]:
# if not exist, give a default value
print getattr(obj, 'my_name', 'default_value')


default_value

1.3 object function

By calling getattr function, you will get the function object


In [43]:
getattr(obj, 'do_foo')()


foo

In [44]:
print getattr(obj, 'do_bar')()


bar

In [45]:
getattr(obj, 'do_two')('gaufung')


gaufung

In [46]:
getattr(obj, 'names')


Out[46]:
'object'

1.4 class method and static method


In [16]:
getattr(obj, 'class_bar')()


class_bar

In [17]:
getattr(obj, 'static_foo')()


static_foo

2 hasattr


In [28]:
hasattr(obj, 'do_bar')


Out[28]:
True

In [29]:
hasattr(obj, 'gaofeng')


Out[29]:
False

3 setattr


In [33]:
setattr(obj, 'name', 'gaufung')
print hasattr(obj, 'name')
print getattr(obj, 'name')


True
gaufung

In [34]:
def add(x, y):
    return x+y

setattr(obj, 'add', add)
print getattr(obj, 'add')(2,1)


3

4 delattr


In [36]:
print hasattr(obj, 'add')


True

In [37]:
delattr(obj, 'add')
print hasattr(obj, 'add')


False

5 eval


In [38]:
func_name = 'add'
eval(func_name)(1,2)


Out[38]:
3