Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.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_Python 3.x_Methods - Fatal编程技术网

Python 理解类方法:方法调用错误

Python 理解类方法:方法调用错误,python,class,python-3.x,methods,Python,Class,Python 3.x,Methods,在创建自己的类时,我很难理解方法是如何工作的 这是我的课堂教学方法: def compare_coll(self,coll_1, coll_2) -> None: ''' compares two collections of key words which are dictionaries, <coll_1> and <coll_2>, and removes from both collections every word that

在创建自己的类时,我很难理解方法是如何工作的

这是我的课堂教学方法:

def compare_coll(self,coll_1, coll_2) -> None:
    '''  compares two collections of key words which are dictionaries, 
    <coll_1> and <coll_2>, and removes from both collections every word 
    that appears in both collection'''


    overlap = set(coll_1).intersection(set(coll_2))
    for key in overlap:
        del coll_1[key], coll_2[key]
产生:

Traceback (most recent call last):
File "<string>", line 1, in <fragment>
builtins.TypeError: compare_coll() missing 1 required positional argument: 'coll_2'
产生了同样的错误


我不确定如何在shell中使用它。

您的
compare\u coll
方法是一个实例方法,而不是类方法。实例方法的第一个参数,按惯例称为
self
,始终是从中调用该方法的类的实例(例如
self==c1
,用于
c1.compare\u coll(c2)
),因此您只需要提供一个其他参数。尝试:

def compare_coll(self, other) -> None:
    overlap = set(self.counts).intersection(set(other.counts))
    for key in overlap:
        del self.counts[key], other.counts[key]
这将适用于
c1。比较\u coll(c2)
收集\u单词\u计数。比较\u coll(c1,c2)


请注意,我已经为方法中的两个实例中的每一个直接引用了
计数。

我想我对类方法和实例方法之间的区别有点困惑,但我将做一些进一步的研究。对于这一点和:
>>> Collection_of_word_counts.compare_coll(c1,c2)
def compare_coll(self, other) -> None:
    overlap = set(self.counts).intersection(set(other.counts))
    for key in overlap:
        del self.counts[key], other.counts[key]