我尝试通过此视频学习 OOP https://www.youtube.com/watch?v=Ej_02ICOIgs&t=143s&ab_channel=freeCodeCamp.org
1:30:00 是与我的问题相关的内容,但在这个代码片段中,我将删除与问题无关的任何内容,并且代码片段本身应该提供足够的上下文。
我的父类以名称、价格和数量作为参数。 我的子班有一个独特的参数,称为“broken_phone”。 问题集中在 repr
这是视频中显示的代码(排除不相关的内容)
class Item:
all = []
def __init__(self, name:str , price: float , quantity:int):
#Assign to self object
self.name = name
self.price = price
self.quantity = quantity
#action to execute
Item.all.append(self)
def __repr__(self):
return f'{self.__class__.__name__}("{self.name}", {self.price}, {self.quantity})'
class Phone(Item):
def __init__(self, name:str , price: float , quantity:int, broken_phone=0):
#call to super function to have access to all attributes
super().__init__(
name, price, quantity
)
#Assign to self object
self.name = name
self.price = price
self.quantity = quantity
所以子类(Phone)也应该从父类(Item)继承repr,但是当我调用Phone.all时,它只返回
f'{self.__class__.__name__}("{self.name}", {self.price}, {self.quantity})'
排除子类参数(broken_phone)是正常做法吗?子类的争论不应该是这样的吗?
f'{self.__class__.__name__}("{self.name}", {self.price}, {self.quantity}, {self.broken_phone})'
所以我的问题是,这样排除它正常吗?如果没有,我应该如何解决这个问题。该视频只是告诉我只在父类中使用repr,而不解决这个问题。
这样排除是正常的吗?
是的
Phone
没有定义自己的 __repr__
方法,因此它使用从 Item
继承的方法,它不知道关于 broken_phone
属性的任何信息。
__repr__
并不像您所期望的那样简单地打印所有当前实例属性。 (即使这样做了,Phone.__init__()
实际上并没有将broken_phone
参数保存在任何地方。它根本不被使用。)