gpt4 book ai didi

Python属性报错对象没有属性

转载 作者:太空宇宙 更新时间:2023-11-03 15:10:50 26 4
gpt4 key购买 nike

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

 class Organization(object):
__employees=[]

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

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

最佳答案

好吧,您已将其声明为私有(private)变量。

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

关于Python属性报错对象没有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27054963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com