从超类返回__str__时出错



我的代码输出不准确。当它调用时

super().__str__()

输出为

<__main__.Trip object at 0x00000251D30D5A30>

输出应为

Driver Id: 1 Name: John Contact: 82121355
<小时 />
from datetime import datetime
class Driver:
_nextId = 1
def __init__(self,name,contact):
self._name = name
self._contact = contact
self._driverId = Driver._nextId
Driver._nextId += 1
@property
def driverId(self):
return self._driverId
@property 
def name(self):
return self._name
@property
def contact(self):
return self._contact
@contact.setter
def contact(self, newContact):
self._contact = newContact
def __str__(self):
return f'Driver Id: {self._driverId} Name: {self._name} Contact: {self._contact}'
class Trip:
def __init__(self,tripDate,startPoint,destination,distance,driver):
self._tripDate = tripDate
self._startPoint = startPoint
self._destination = destination
self._distance = distance
self._driver = driver
@property
def tripDate(self):
return self._tripDate
@property
def destination(self):
return self._destination
@property
def driver(self):
return self._driver

def __str__(self):
return f'{self._tripDate}, From: {self._startPoint} To: {self._destination}n Distance: {self._distance}km' + super().__str__()
if __name__ == '__main__':
d1 = Driver('John','82121355')
t1 = Trip(datetime(2021,5,30,17,45),'Empire State Building','Rockerfeller Centre','2.25',d1)
print(t1)

Trip代码中的问题:

def __str__(self):
return f'...' + super().__str__()

Trip不是Driver的子类,也不是从Driver继承任何东西。super调用不会调用Driver__str__方法,而是调用所有 Python 类的默认/内置object.__str__(self)

>>> class XYZ: pass
... 
>>> obj1 = XYZ()
>>> print(obj1)
<__main__.XYZ object at 0x10e28b040>

仅当您的类是另一个类的子类时,该super()才有效:

>>> class Animal:
...   def __str__(self):
...     return 'Animal __str__'
... 
>>> class Dog(Animal):
...   def __str__(self):
...     return f'{super().__str__()} + Dog __str__'
... 
>>> d = Dog()
>>> print(d)
Animal __str__ + Dog __str__

我不知道你为什么期望Trip的超类是Driver的,因为行程不是驱动程序,而是涉及DriverTrip,所以你当前使用驱动程序实例化行程的实现是有意义的。

您唯一需要更改的是将super()替换为self._driver,这是您传递给TripDriver实例。

# super().__str__() --> self._driver.__str__()
def __str__(self):
return f'{self._tripDate}, From: {self._startPoint} To: {self._destination}n Distance: {self._distance}km' + self._driver.__str__()
2021-05-30 17:45:00, From: Empire State Building To: Rockerfeller Centre
Distance: 2.25kmDriver Id: 1 Name: John Contact: 82121355

或者更简单地说:

# super().__str__() --> str(self._driver)
# And put it inside the f-string
def __str__(self):
return f'{self._tripDate}, From: {self._startPoint} To: {self._destination}n Distance: {self._distance}km {str(self._driver)}'
2021-05-30 17:45:00, From: Empire State Building To: Rockerfeller Centre
Distance: 2.25km Driver Id: 1 Name: John Contact: 82121355

因为 Python 的str(obj)调用该对象的__str__方法。

相关内容

最新更新