【问题标题】:Trying to Understand This Line in the Code试图理解代码中的这一行
【发布时间】: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,而helloSpecialString 的一个实例。
  • @ChootsMagoots 是的,有证据:print(spam / hello) 正在调用spam.__truediv__(hello),而helloSpecialString 的一个实例。

标签: python class oop


【解决方案1】:

truediv() 特殊方法仅与 / 运算符一起使用。

下面是我如何分解 truediv。这基本上称为运算符重载。

def __truediv__(self, SpecialString("Hello world!")):
    #line = "=" * len(other.cont)
    line = "=" * len(SpecialString("Hello world!").cont)

    #return "\n".join([self.cont, line, other.cont])
    return "\n".join([SpecialString("spam").cont, line, SpecialString("Hello world!").cont])

这里的其他是正在传递的第二个类实例。

SO中有一个问题详细回答了truediv()的运算符重载。你可以在这里查看:operator overloading for __truediv__ in python

【讨论】:

  • 后续问题,那.cont有什么用呢?似乎line 只是用来设置= 的数量,你为什么需要.cont?那是字符串吗?
  • .cont 目前有两个用途。要设置= 计数,最后,您将使用.cont 变量打印值。
【解决方案2】:

该方法需要两个对象实例作为参数,selfother。代码并不关心other 属于哪个类,只要它也有一个cont 属性,它有一个长度。但除法通常需要两个相同类型的对象。

(当不同类型的对象与您的行为相同时,这称为多态性。此时理解这一点并不重要,但您可能已经遇到过这个概念。)

【讨论】:

    猜你喜欢
    • 2012-02-17
    • 2019-08-30
    • 2011-05-17
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    相关资源
    最近更新 更多