我的代碼輸出不準確。當它呼叫
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)
uj5u.com熱心網友回復:
您Trip的代碼中的問題:
def __str__(self):
return f'...' super().__str__()
是,Trip是不是的一個子類Driver,也不做它繼承任何東西Driver。該super呼叫不會呼叫Driver的__str__方法,而是呼叫object.__str__(self)所有 Python 類的默認/內置方法:
>>> 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,因為 trips 不是驅動程式,而是 aTrip涉及 a Driver,所以你當前的實作,你實體化一個帶有驅動程式的旅行是有道理的。
您唯一需要更改的是替換super()為self._driverwhich 是Driver您傳遞給Trip.
# 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
因為 Pythonstr(obj)呼叫了該物件的__str__方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/363987.html
