【发布时间】:2018-11-23 04:34:33
【问题描述】:
我现在正在学习 Python 类,遇到了一个书上没有解释太多的东西。
我有一个代码:
class Human(object):
def __init__(self,*args,**kwargs):
self.first_name = kwargs.setdefault('first')
self.last_name = kwargs.setdefault('last')
self.height = kwargs.setdefault('height')
self.weight = kwargs.setdefault('weight')
def bmi(self):
return self.weight/float(self.height)**2
Human.bmi = bmi
def human_str(self):
return '{} {}'.format(self.first_name, self.last_name)
Human.__str__ = human_str
me = Human(first='Seth', last='Gibson')
adam_mechtley = Human(first='Adam', last='Mechtley', weight = 78, height = 1.85)
sis = Human(first='Ruth',last='Gibson')
babysis = Human(first='Emily',last='Gibson')
print(sis)
#Prints : proper name
print(sis,babysis)
#Prints : <place in memory>
我总体上了解正在发生的事情,但是 问题是,为什么当我只打印一个实例时, str() 属性有效,但如果我尝试同时打印两个实例, repr() 属性是正在使用?
感谢您的宝贵时间!
【问题讨论】:
-
这肯定是定义类的倒退方式
-
如果这是 Python 3,我会说
print(x)使用__str__,而print((x,y))调用tuple的__str__,内部调用元素的__repr__,但它不会在 Python 2 中打印(...),即不是元组。可能还是那样。 -
无法复制。当我在 Python 2.7.10 中运行此代码时,我得到
Ruth Gibson<newline>Ruth Gibson Emily Gibson作为输出。 -
实际上,经过仔细检查,我也无法重现问题,使用
Python 2.7.15rc1,既不是这种“向后”方式,也不是正确的def __str__(self),也不是str和@ 987654333@. -
对不起,伙计们犯了一个小错误,而不是 'print sis' 和 'print sis,babysis',应该是 'print(sis)' 和 'print(sis,babysis)'。很抱歉造成混淆,括号不见了。那么我的问题就有意义了。