Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 试图理解代码中的这一行_Python_Class_Oop - Fatal编程技术网

Python 试图理解代码中的这一行

Python 试图理解代码中的这一行,python,class,oop,Python,Class,Oop,我对Python有点陌生,刚开始接触面向对象。我想我理解基本的代码,但这一行代码确实让我感到困惑 以下是整篇文章: class SpecialString: def __init__(self, cont): self.cont = cont def __truediv__(self, other): line = "=" * len(other.cont) return "\n".join([self.cont, line, o

我对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)
我不明白“其他”是什么意思。一个对象如何成为另一个对象的属性?或者“cont”只是应用在“other”上?

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()的运算符重载。您可以在此处进行检查:

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


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

将一个对象作为另一个对象的属性没有问题,但在本例中,它只是引用一个不同的对象
.cont
属性。您正在传递other,这是一个函数,它有一个名为other.cont的属性。因此,在本例中,您引用的是另一个函数中的属性。这在Python中是可以的。@SimeonIkudabo您正在传递other,这是一个函数为什么other必然是一个函数?@SimeonIkudabo
other
不是一个函数。他将
hello
作为
other
传递,而
hello
SpecialString
@ChootsMagoots的一个实例是有证据的:
print(spam/hello)
正在调用
spam.\uu truediv(hello)
,而
hello
SpecialString
的一个实例。跟进问题,那么
.cont
有什么用呢?似乎
只是用来设置
=
的编号,您需要什么
.cont
?这是字符串吗?
.cont
现在有两个用途。要设置
=
计数,最后使用
.cont
变量打印值。