Skip to main content
 首页 » 编程设计

python之如何获取变量的名称

2025年05月04日9tintown

我正在练习用 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) 

实例本身无法知道您为包含它的变量指定的名称。因此,将名称存储在实例中。