如何在python中打印可打印的对象信息
见:如何在python中打印可打印的对象信息,python,object,Python,Object,见: >>A类: ... a=3 ... >>>tmp=A() >>>tmp >>>A >>>tmp.a 3. 我想要tmp.a也有像'tmp'和'a'这样的输出,这是可能的吗 请注意,这就像tmp不在tmp中一样。所以我想要的是: >>> class A: ... a = 3 ... >>> tmp=A() >>> tmp <__main__.A instance at 0xb7340c2c> >&g
>>A类:
... a=3
...
>>>tmp=A()
>>>tmp
>>>A
>>>tmp.a
3.
我想要tmp.a也有像'tmp'和'a'这样的输出,这是可能的吗
请注意,这就像tmp不在tmp中一样。所以我想要的是:
>>> class A:
... a = 3
...
>>> tmp=A()
>>> tmp
<__main__.A instance at 0xb7340c2c>
>>> A
<class __main__.A at 0xb733c26c>
>>> tmp.a
3
>tmp.a
每个对象可以有一个\uuuu str\uuuu
,您还可以定义一个\uuuu repr\uuuu
方法,该方法将被打印出来
>>> tmp.a
<int tmp.a at ...>
每个对象都可以有一个
\uuuu str\uuuu
,您还可以定义一个\uuuuu repr\uuuuu
方法,该方法将被打印出来
>>> tmp.a
<int tmp.a at ...>
否,
tmp.a
是一个整数对象。它将像任何其他整数对象一样显示。但是,您可以定义使用函数来获取a
的表示形式
>>> class A(object):
... a = 3
... def __str__(self):
... return repr(self)+': a: %d' % self.a
... def __repr__(self):
... return 'A object with id %d ' % id(self)
...
>>> b=A()
>>> b
A object with id 4340531472
>>> print b
A object with id 4340531472 : a: 3
任何对象的“可打印信息”实际上由\uuuu repr\uuuu
或\uu str\uuu
功能控制。所以,你可以简单地定义它
class A:
a = 3
def repr_a(self):
return repr(self) + ': a: ' + str(self.a)
否,
tmp.a
是一个整数对象。它将像任何其他整数对象一样显示。但是,您可以定义使用函数来获取a
的表示形式
>>> class A(object):
... a = 3
... def __str__(self):
... return repr(self)+': a: %d' % self.a
... def __repr__(self):
... return 'A object with id %d ' % id(self)
...
>>> b=A()
>>> b
A object with id 4340531472
>>> print b
A object with id 4340531472 : a: 3
任何对象的“可打印信息”实际上由\uuuu repr\uuuu
或\uu str\uuu
功能控制。所以,你可以简单地定义它
class A:
a = 3
def repr_a(self):
return repr(self) + ': a: ' + str(self.a)
不能不绑定
tmp.a
到其他东西..不能不绑定tmp.a
到其他东西。。