如何获取变量的名称

时间:2014-08-04 00:36:52

标签: python function class

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

如何将变量名称输入方法?

6 个答案:

答案 0 :(得分: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)

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

答案 1 :(得分:3)

从根本上说,你不能在这里做你想做的事,因为在Python中,名称不是变量的属性。它只是一个句柄,可以附加和重新附加,而对象可以有多个指向它的名称,其中没有一个是 名称。

这就是其他人建议添加名称作为init参数的原因。

答案 2 :(得分:2)

如果我要做你正在做的事情,我会改变你的课程来做类似的事情:

class GolfClub:
    def __init__(self, size, distance):
        self.size = size
        self.distance = distance

    def hits_further(self, other):
        if self.distance > other.distance:
            return True
        else:
            return False

代码可以执行以下操作:

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

if club1.hits_further(club2):
    print("club1 hits further")
else:
    print("club2 hits further")

答案 3 :(得分:2)

将return语句更改为print语句。

为您的班级添加name属性。然后做这样的事情:

class GolfClub:
    def __init__(self, size, distance,name):
        self.size = size
        self.name = name
        self.distance = distance

    def hits_further(self, other):
        if self.distance > other.distance:
            print self.name, "club hits further"
        else:
            print other.name ,"That club hits further"

club1 = GolfClub(5, 200,"c1")
club2 = GolfClub(6, 300,"c2")

club1.hits_further(club2)

据我所知,你希望实现的目标是不可能的

答案 4 :(得分:2)

事实上,可以通过询问堆栈来完成

import inspect
import traceback
import sys
import re

class GolfClub:
    def __init__(self, size, distance):
        self.size = size
        self.distance = distance

    def hits_further(self, other):
        call_str= traceback.extract_stack()[0][3]
        m = re.search('([\w]+)\.hits_further\((.*)\)',call_str)

        self_name=m.group(1)
        other_name=m.group(2)
        if self.distance > other.distance:
            return self_name+" hits further"
        else:
            return other_name+" hits further"

club1=GolfClub(1,1)
club2=GolfClub(2,2)
print club1.hits_further(club2)
print club2.hits_further(club1)

结果是:

club2 hits further
club2 hits further

按照geogeogeo的要求

答案 5 :(得分:0)

你可以这样:

def name(**variable):
    return [x for x in variable]