如何获取变量的名称

geo*_*geo 1 python class function

我正在练习用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"
Run Code Online (Sandbox Code Playgroud)

如果我做:

club1 = GolfClub(5, 200)
club2 = GolfClub(6, 300)

club1.hits_further(club2)
Run Code Online (Sandbox Code Playgroud)

如何使hits_further方法返回变量的名称?例如,我希望它返回:

"club2 hits further"
Run Code Online (Sandbox Code Playgroud)

如何将变量名称放入方法中?

Jos*_*ton 5

传统上,您将为实例指定一个名称:

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)
Run Code Online (Sandbox Code Playgroud)

实例本身无法知道您给包含它的变量赋予了什么名称.因此,将名称存储在实例中.