【发布时间】:2018-05-30 17:32:38
【问题描述】:
我对 Python 有点陌生,刚刚接触到面向对象。我想我了解基本的,但这行代码真的让我很困惑。
这是整个片段:
class SpecialString:
def __init__(self, cont):
self.cont = cont
def __truediv__(self, other):
line = "=" * len(other.cont)
return "\n".join([self.cont, line, other.cont])
spam = SpecialString("spam")
hello = SpecialString("Hello world!")
print(spam / hello)
我说的是这个:
line = "=" * len(other.cont)
我不明白“other.cont”是什么意思。一个对象怎么可能是另一个对象的属性?还是“cont”只是应用于“other”?
【问题讨论】:
-
将一个对象作为另一个对象的属性没有问题,但在这种情况下它只是引用不同的对象
.cont属性 -
你正在传递 other,这是一个函数,它有一个名为 other.cont 的属性。因此,在这种情况下,您引用的是另一个函数中的属性。这在 Python 中是可以的。
-
@SimeonIkudabo 你在传递 other,这是一个函数 为什么 other 一定是一个函数?
-
@SimeonIkudabo
other不是函数。他将hello传递为other,而hello是SpecialString的一个实例。 -
@ChootsMagoots 是的,有证据:
print(spam / hello)正在调用spam.__truediv__(hello),而hello是SpecialString的一个实例。