我正在练习用Python编写类,却对如何做某事感到困惑。
class GolfClub:
def __init__(self, size, distance):
self.size = size
self.distance = distance
def hits_further(self, other):
if self.distance > other.distance:
return "(name of club variable) hits further"
else:
return "(name of club variable) hits further"
如果我做:
club1 = GolfClub(5, 200)
club2 = GolfClub(6, 300)
club1.hits_further(club2)
如何使hits_further方法返回变量的名称?例如,我希望它返回:
"club2 hits further"
如何将变量名输入方法?
传统上,您将为实例命名:
class GolfClub:
def __init__(self, name, size, distance):
self.name = name
self.size = size
self.distance = distance
def hits_further(self, other):
if self.distance > other.distance:
return "%s hits further" % self.name
else:
return "%s hits further" % other.name
club1 = GolfClub('Driver', 5, 200)
club2 = GolfClub('9Iron', 6, 300)
club1.hits_further(club2)
实例本身无法知道您为包含它的变量指定了什么名称。因此,将名称存储在实例中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句