小编Fil*_*ppo的帖子

__getattr __,newstyle vs oldstyle类的不对称行为

这是我第一次写这篇文章,对不起,如果邮件没有被批评或太长.

我有兴趣了解更多关于如何在需要时获取对象的属性.所以我在这里阅读了标题为"数据模型"的Python 2.7文档,我遇到了__getattr__,为了检查我是否理解了它的行为,我编写了这些简单(和不完整)的字符串包装器.

class OldStr:
  def __init__(self,val):
    self.field=val

  def __getattr__(self,name):
    print "method __getattr__, attribute requested "+name

class NewStr(object):
  def __init__(self,val):  
    self.field=val

  def __getattr__(self,name):
    print "method __getattr__, attribute requested "+name
Run Code Online (Sandbox Code Playgroud)

正如你所看到的那样,除了作为旧式和新式的课程外,它们是相同的.由于引用的文本说__getattr__"当一个属性查找没有找到通常位置的属性时调用",我想在这些类的两个实例上尝试+操作,看看发生了什么,期望相同的行为.

但结果让我感到困惑:

>>> x=OldStr("test")
>>> x+x
method __getattr__, attribute requested __coerce__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
Run Code Online (Sandbox Code Playgroud)

好!我没有定义一个方法__coerce__(虽然我期待一个请求__add__,没关系:),所以__getattr__参与并返回了一个无用的东西.但是之后

>>> y=NewStr("test")
>>> y+y
Traceback (most recent call last):
File …
Run Code Online (Sandbox Code Playgroud)

python coding-style new-operator getattr

8
推荐指数
2
解决办法
1077
查看次数

标签 统计

coding-style ×1

getattr ×1

new-operator ×1

python ×1