关于ZAKER 融媒体解决方案 合作 加入

Python 属性错误对象没有属性

CocoaChina 10-23

当我应用两个下划线时 , 出现错误 AttributeError:’ Organization ’对象没有属性’ __employees ’

这是代码 .

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

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

最佳答案

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

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

Python doc年代开始:

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.

以上内容由"CocoaChina"上传发布 查看原文

觉得文章不错,微信扫描分享好友

扫码分享