我有这个代码,带有所需的输出"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()的括号之间输入的实际字母并打印出来。
对我来说,这听起来像是一个简单的事情,在调试和检查我的代码时非常有用,所以我可以准确地告诉对象做了什么。我在假设中犯了一个根本性的错误,这是一个可怕的想法吗?
答案 0 :(得分: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可能this page。
如果您只想要比<__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')