我正在尝试在函数中创建项目对象,但是当我尝试打印出项目属性时,会出现错误。
Traceback (most recent call last):
File ".\AddSales.py", line 184, in <module>
if (collectSerials(salesOrderInfo[0], salesOrderInfo[1], salesOrderInfo[2], itemInfo[0], itemInfo[1] ,itemList) == 1):
File ".\AddSales.py", line 62, in collectSerials
print(item.getName())
File ".\AddSales.py", line 109, in getName
return self.__name
AttributeError: 'Item' object has no attribute '_Item__name'
对象: 课程项目:
def __init__(self, name, serialNumber, salesOrderNumber, shippingDate, salesInfo, warrantyExpiration):
self.name = name
self.serialNumber = serialNumber
self.salesOrderNumber = salesOrderNumber
self.shippingDate = shippingDate
self.salesInfo = salesInfo
self.warrantyExpiration = warrantyExpiration
功能:
def collectSerials(salesOrderNum, shipDate, info, name, warranty, workingList=None):
while 1:
sn = input("Scan in the item's serial number, or enter \"done\" if finished scanning: \n")
if (sn == "done"):
break
item = Item(name, sn, salesOrderNum, shipDate, info, warranty)
print(item.getName())
if (workingList is None):
workingList = []
workingList.append(item)
answer = input("Choose between the following options (Enter the corresponding number): \n1) Enter a different product \n2)Exit and finish sales order\n")
return answer
函数调用:
collectSerials(salesOrderInfo[0], salesOrderInfo[1], salesOrderInfo[2], itemInfo[0], itemInfo[1] ,itemList)
答案 0 :(得分:1)
在Python中为属性名称加上两个下划线(仅)时,会触发一个称为名称处理的特殊功能。 Python没有真正的私有属性。相反,Python通过尝试隐藏“私有”属性来实现。这是通过将属性名称与类名称混合在一起来实现的。该错误表明您正在尝试访问其定义以外的类的__item
。给定以下类:
class MyObject:
def __init__(self):
self.__private = object()
def get_private(self):
return self.__private
__private
实际上存储为_MyObject__private
。
obj = MyObject()
assert obj._MyObject__private is obj.get_private()
如上所述,在类上定义的函数范围之外,仍然可以访问该属性。您只需要知道该怎么称呼。
这意味着,如果您尝试从另一个类(例如子子类)访问此类属性,则可能会出错。 Python不知道您的意思是访问另一个类的“私有”属性,因此该名称将与当前类混淆。例如。
class MyChild(MyObject):
def swap_private(self, replacement):
old = self.get_private()
# works! get_private is defined on MyObject and so fetches _MyObject__private
self.__private = replacement
# silent error! Would actually store replacement in _MyChild__private
return old
def set_private(obj, replacement):
obj.__private = replacement
# silent error! This function is not defined on a class and so just tries to directly
# access `__private`
简单的解决方案是除非绝对必要,否则不要使用双下划线名称。如果要将属性标记为私有,则只需使用一个下划线。