本文介绍了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:

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

07-05 07:33