【问题标题】:How can I turn one of the arguments of a function into a string?如何将函数的参数之一转换为字符串?
【发布时间】:2016-01-16 23:54:43
【问题描述】:

我有这个代码,需要输出"The value is Bar and the name is b."

class myClass:
    def __init__(self, value):
        self.value = value

b = myClass("Bar")

def foo(var):
    true_name = str(var)
    print("The value is %s and the name is %s" % (var.value, true_name))

foo(b)

但是,这会打印出The value is Bar and the name is <__main__.myClass object at 0x000000187E979550>,这对我来说用处不大。

现在,I know the problems with trying to get the true name of a variable in Python。但是,我不需要做任何花哨的内省;我只想转换在 foo() 括号之间输入的实际字母并打印出来。

对我来说,这听起来很简单,在调试和检查我的代码时很有用,所以我可以准确地知道是什么对象做了一件事情。我的假设是否存在根本性错误,这是一个糟糕的想法?

【问题讨论】:

  • 没有简单的方法可以做你想做的事。变量名不是数据,您不需要知道它们。如果您希望您的对象具有名称,请将“名称”设置为属性或其他内容。
  • 你从来没有提到你是怎么打电话给foo的。那个特定电话中的var 是什么?
  • @TigerhawkT3:修复! varb,所以 foo(b)
  • @TigerhawkT3:是的。我将所需的输出放在问题的顶部,以防您错过。
  • 如果你想要一种人类友好的方式来输出一个值,请为其类编写一个__str____repr__ 方法。不要将对象与其变量名混淆,它们不是一回事。一个对象可能有一个名称,但也可能没有(如foo(MyClass("Bar")))或多个名称,如a = b = MyClass("Bar"))。

标签: python oop


【解决方案1】:

最简单的方法是简单地将所需的“真实姓名”与实际参考一起传递:

def foo(var):
    var, true_name = var
    print("The value is %s and the name is %s" % (var.value, true_name))

foo((b, 'b'))

当然,这并不能保证true_name 与传递的引用名称匹配,但与possibly-fragile hacks 可能或可能not work 相比,它是一种更短更清晰的不保证方法。

如果你只是想要比<__main__.myClass object at 0x000000187E979550> 更易读的东西,你应该在你的类中定义一个__str__ 方法,然后简单地打印实例。您甚至不再需要单独的 foo 函数。您还可以为精确表示定义 __repr__ 方法(这是您将输入解释器以生成等效对象的字符串):

class myClass:
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return 'myClass with a value of {}'.format(self.value)
    def __repr__(self):
        return "myClass({})".format(repr(self.value))

结果:

>>> b = myClass("Bar")
>>> print(b)
myClass with a value of Bar
>>> b
myClass('Bar')

【讨论】:

    最近更新 更多