开发者

object properties in python

   class test:
      a="hi"

      def msg(self):
          print the variable for which the object is referring 开发者_开发技巧to

   t= test()
    print t.b

From the above code is there any way to tell that the object is referring to a variable b which does not exist


Use the __getattr__ method, see documentation:

In [1]: class test(object):
   ...:     a = 'hi'
   ...:     def __getattr__(self, val):
   ...:         print 'you are accessing ', val
   ...:         
   ...:         

In [2]: t = test()

In [3]: t.b
you are accessing  b

In [4]: t.c
you are accessing  c

In [5]: t.a
Out[5]: 'hi'

EDIT:

class test(object):
    a = 'hi'

    def msg(self, var, default='undefined'):
        setattr(self, var, default)
        return default

    def __getattr__(self, val):
        print 'attribute %s not found, setting..' % val
        return self.msg(val)


>>> t = test()
>>> print t.a
'hi'
>>> print t.b
'attribute b not found, setting..'
'undefined'
>>> t.b = 'this is black magic'
>>> # notice no message is printed here about attribute not found
>>> print t.b
'this is black magic'

EDIT2:

>>> d = {'a': '1'}
>>> d.setdefault('b', 'b')
'b'
>>> d
{'a': '1', 'b': 'b'}
>>> d.setdefault('a', 'b')
'1'
>>> d
{'a': '1', 'b': 'b'}


Yes. You will get a NameError on the print b line, and an AttributeError on the print t.b line.

You can catch these exceptions like this:

try:
    print t.b
except AttributeError as e:    # or `except AttributeError, e` on Python < 2.6
    # Do something...


This should do it.

class tester(object):
    a = 'hi'

    def __getattr__(self, val):
        print 'accessing attribute %s failed!' % val

>>> t = tester()
>>> t.a
'hi'
>>> t.b
accessing attribute b failed!
>>> 

EDIT: Removed some redundant code


If that's all the code, then of course there is no b. But, I assume that you want us to assume there could be more code. If there is, or perhaps if this code is imported as a module by other code, then there is no way to tell until it is run.


All members of an object are stored in that objects __dir__. So you can just do this:

>>> "msg" in dir(t)
True
>>> "b" in dir(t)
False

This works for the standard case, and may behave differently if descriptors are involved, or __getattr__ or __getattribute__ are overloaded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜