python中的对象属性

python中的对象属性,python,Python,从上面的代码可以看出对象引用的是不存在的变量b如果这就是所有的代码,那么当然就没有b。但是,我假设你想让我们假设可能有更多的代码。如果有,或者如果此代码被其他代码作为模块导入,则在运行之前无法判断。是。您将在print b行获得namererror,在print t t.b行获得AttributeError 您可以像这样捕获这些异常: class test: a="hi" def msg(self): print the variable fo

从上面的代码可以看出对象引用的是不存在的变量b

如果这就是所有的代码,那么当然就没有
b
。但是,我假设你想让我们假设可能有更多的代码。如果有,或者如果此代码被其他代码作为模块导入,则在运行之前无法判断。

是。您将在
print b
行获得
namererror
,在
print t t.b
行获得AttributeError

您可以像这样捕获这些异常:

   class test:
      a="hi"

      def msg(self):
          print the variable for which the object is referring to

   t= test()
    print t.b
试试看:
打印t.b
在Python<2.6版本中,除AttributeError外的值为e:#或除AttributeError外的值为e`
#做点什么。。。

使用
\uuu getattr\uuu
方法,请参阅:

编辑:

编辑2:

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'
这应该可以做到

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

编辑:删除一些冗余代码

对象的所有成员都存储在该对象中。所以你可以这样做:

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!
>>> 

这适用于标准情况,如果涉及描述符,或者
\uuu getattr\uuuuu
\uuuu getattribute\uuuuu
重载,则可能会表现不同。

如果引用一个不存在的变量,则会得到
attributererror
。在hasattr(t,'b')语句中,“请求原谅比请求许可更容易”我们不能从对象本身获取变量,而不是硬编码b吗?对象如何知道变量b被引用?请澄清您的意思?在您的问题中,您询问了如何检查对象是否引用了不存在的变量b@Cameron的回答向您展示了如何捕捉异常。你到底想做什么?在我的课堂上,我需要打印对象引用的是一个不存在的变量。请看问题中的编辑哦,我明白了。更新答案。对象如何知道其引用的变量不存在,并且正在复制标准行为。那有什么用?打得好。我没有意识到这一点。谢谢第一行不正确,正如你在最后一行中所说的那样<代码>\uuuuu dir\uuuuu是对象报告其希望您了解的属性的一种方式。
>>> d = {'a': '1'}
>>> d.setdefault('b', 'b')
'b'
>>> d
{'a': '1', 'b': 'b'}
>>> d.setdefault('a', 'b')
'1'
>>> d
{'a': '1', 'b': 'b'}
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!
>>> 
>>> "msg" in dir(t)
True
>>> "b" in dir(t)
False