![](/img/trans.png)
[英]Python: How to use __add__ special method to add instances of the same class that return another instance of that class
[英]How to use to instances of a class in a clas method python?
我有一輛汽車 class,其中汽車名稱和速度作為實例變量,在 class 中,我有一個方法可以返回給定兩個汽車對象的汽車更快。 我想構建一個方法,在不使用實例變量的情況下返回哪輛車更快,而不是使用 getter 來獲取汽車 object 的速度,然后在計算中使用它。
您可以使用重載__gt__
、 __lt__
和__eq__
方法比較 class 的兩個對象。 我在這個例子中重載了__gt__
方法:
class Car:
def __init__(self, name, speed):
self.name = name
self.speed = speed
def __gt__(self, other):
return self.speed>other.speed
c1 = Car("ferry", 300)
c2 = Car("pride", 30)
if c1>c2:
print(f"{c1.name} is faster than {c2.name}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.