Python属性错误对象没有属性 [英] Python attribute error object has no attribute

查看:674
本文介绍了Python属性错误对象没有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我应用两个下划线时,出现错误AttributeError: 'Organization' object has no attribute '__employees' 这是代码.

When I apply two underscores I get the error AttributeError: 'Organization' object has no attribute '__employees' Here is the code.

 class Organization(object):
        __employees=[]

    google=Organization()
    google.__employees.append('Erik')

Python没有实现私有变量的概念.如果是这样,我得到错误.如果我删除了一个下划线代码,则执行时不会出现错误.

Python doesn't implement private variable concept. If so what I get error. If I remove one underscore code execute without an error.

推荐答案

好,您已经将其声明为私有变量.

Well you have declared it as a private variable.

>>> class Organization(object):
...     __employees = []
... 
>>> google = Organization()
>>> google._Organization__employees.append('Erik')
>>> google._Organization__employees
['Erik']

>>> dir(Organization)
['_Organization__employees', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

如您所见,它使用 _Classname__Variablename 保存您的副名称. 您的情况是 _Organization__employees .

As you can see it save your vairable name with _Classname__Variablename. In your case it is _Organization__employees.

来自 Python文档 s:

形式为__spam的任何标识符(至少两个下划线, 在文本上最多替换一个结尾的下划线) _classname__spam,其中classname是当前的类名,其中前导下划线被去除.这种处理是无视的 到标识符的句法位置,因此可以用来 定义类私有实例和类变量,方法,变量 存储在全局变量中,甚至变量存储在实例中.私人 该类在其他类的实例上.

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

这篇关于Python属性错误对象没有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆