简体   繁体   English

Python3:传递函数名称作为争论

[英]Python3:Passing function name as arguement

I am learning python oop concepts and stumbled upon below code that I am trying to write. 我正在学习python oop概念,并偶然发现了以下我要编写的代码。 There is a class Sort which has different methods of sorting and a generic function sort. 有一个Sort类,它具有不同的排序方法和通用函数排序。

class Sort:
    def __init__(self, numlist):
        self.numlist = numlist

    def msort(self, beg, end, reverse=False): #merge sort
        if beg < end:
             mid = (beg + end)//2

             self.msort(beg, mid, reverse)
             self.msort(mid+1, end, reverse)
             self.__merge(beg, mid, end, reverse)


    def isort(self, beg, end, reverse=False): #insertion sort
        i = beg #initial index
        for key in numlist[beg+1:end+1]: #from beg+1 to end
            i = i+1 #current index in numlist
            j = i-1
            if reverse:
                while j >= beg and self.numlist[j] < key:
                    self.numlist[j+1] = self.numlist[j]
                    j = j-1
                self.numlist[j+1] = key
            else:
                while j >= beg and self.numlist[j] > key:
                    self.numlist[j+1] = self.numlist[j]
                    j = j-1
                self.numlist[j+1] = key


    def sort(self, beg, end, func=msort, reverse=False):
        print('Calling {0}()'.format(func))
        func(self, beg, end, reverse)

if __name__ == '__main__':
    numlist = [3, 4, 2, 5, 9, 7, 1, 6]
    s = Sort(numlist)
    s.sort(0, len(numlist)-1, func=isort, reverse=False)
    print(s.numlist, end='')

I have following questions - 1. In main, if I just call s.sort(0, len(numlist)-1, reverse=False) it properly calls msort and gives the result but if I call like s.sort(0, len(numlist)-1, func=isort, reverse=False) it gives below error - 我有以下问题-1.在主要情况下,如果我仅调用s.sort(0,len(numlist)-1,reverse = False),它将正确调用msort并给出结果,但如果我像s.sort(0, len(numlist)-1,func = isort,reverse = False)它给出以下错误-

Traceback (most recent call last): File "Sort.py", line 76, in s.sort(0, len(numlist)-1, func=isort, reverse=False) NameError: name 'isort' is not defined 追溯(最近一次呼叫最近):文件“ Sort.py”,第76行,位于s.sort(0,len(numlist)-1,func = isort,reverse = False)NameError:未定义名称'isort'

I understand why it doesn't work but not able understand why msort works fine. 我了解为什么它行不通,但无法理解为什么msort可以正常工作。

  1. If I call s.sort(0, len(numlist)-1, func=s.isort, reverse=False) then I get below error - 如果我调用s.sort(0,len(numlist)-1,func = s.isort,reverse = False)然后我得到以下错误-

Calling main.Sort object at 0x031BF830>>() Traceback (most recent call last): File "Sort.py", line 76, in s.sort(0, len(numlist)-1, func=s.isort, reverse=False) File "Sort.py", line 71, in sort func(self, beg, end, reverse) TypeError: isort() takes from 3 to 4 positional arguments but 5 were given 调用main.Sort对象,地址为0x031BF830 >>()追溯(最近一次调用):文件“ Sort.py”,第76行,位于s.sort(0,len(numlist)-1,func = s.isort,反向= False)文件“ Sort.py”,第71行,按func(self,beg,end,reverse)排序TypeError:isort()接受3到4个位置参数,但给出了5个

Not able to understand what is happening here. 无法了解这里发生了什么。 I seems to call isort but why is the parameter mismatch 我似乎叫isort,但为什么参数不匹配

  1. In function sort(), I am not able to call self.func() which again gives attribute error. 在函数sort()中,我无法调用self.func(),这再次导致属性错误。 Is this a bad practice to use self. 使用自我是一种不良习惯吗? while calling other function but calling func() without using self.func()? 同时调用其他函数但不使用self.func()调用func()吗?

Please explain pythonic way of organizing this class and function calling. 请说明组织此类和函数调用的pythonic方式。

msort is resolved within the scope of the class definition so it knows it is Sort.msort . msort在类定义的范围内解析,因此知道它是Sort.msort

To use isort from outside of defining the class you need to use pass Sort.isort . 要从定义类的外部使用isort ,您需要使用pass Sort.isort

When you pass s.isort the method is already bound to the object, so you mustn't pass self as the first parameter. 当您传递s.isort该方法已经绑定到该对象,因此您不能传递self作为第一个参数。

Your error is that isort is an instance method, which means it does not exist outside the scope of the Sort class. 您的错误是isort是一个实例方法,这意味着它不在Sort类范围之外。 You can reference it by using Sort.isort in your main : 您可以通过在main使用Sort.isort来引用它:

s.sort(0, len(numlist)-1, func=Sort.isort, reverse=False)

The reason you got the second error is that s.isort already adds self (where self is s ) to isort 's argument list. 您收到第二个错误的原因是s.isort已经将self (其中selfs )添加到isort的参数列表中。 When you call func(self, ...) you are adding self a second time and so you get a total of 5 arguments. 当您调用func(self, ...)您将第二次添加self ,因此总共有5个参数。

You should change you line func(self, beg, end, reverse) to func(beg, end, reverse) . 您应该将func(self, beg, end, reverse)行更改为func(beg, end, reverse) The self argument is passed automagicly. self参数会自动传递。 I'm able to get it working with s.isort. 我能够与s.isort一起使用。

Thanks for replying. 感谢回复。 Few things are clear to me. 我几乎不了解任何事情。 I also found one mistake in above program that in isort function I am using 我还在上面的程序中发现了一个错误,即我正在使用的isort函数

for key in numlist[beg+1:end+1]: 对于numlist [beg + 1:end + 1]中的键:

which actually should be 实际上应该是

for key in self.numlist[beg+1:end+1]: 对于self.numlist [beg + 1:end + 1]中的键:

I will summarize the findings below - 1. Calling func(self, beg, end, reverse) works if I pass func=Sort.isort in main 2. Calling func(beg, end, reverse) works If I pass func=s.isort in main 我将在下面总结这些发现-1.如果在main中传递func = Sort.isort,则调用func(self,beg,end,reverse)起作用。2.如果传递func = s,则调用func(beg,end,reverse)起作用。 主要是 isoort

I understood above 2 points well. 我对以上两点很了解。

  1. Calling func(beg, end, reverse) doesn't work if I pass func=Sort.isort in main . 如果我在main中传递func = Sort.isort,则无法调用func(beg,end,reverse)。 It gives me error - 它给我错误-

Calling () Traceback (most recent call last): File "Sort.py", line 79, in s1.sort(0, len(numlist)-1, func=Sort.isort, reverse=False) File "Sort.py", line 72, in sort func(beg, end, reverse) File "Sort.py", line 55, in isort for key in self.numlist[beg+1:end+1]: #from beg+1 to end AttributeError: 'int' object has no attribute 'numlist' 调用()追溯(最近一次通话):文件“ Sort.py”,行79,位于s1.sort(0,len(numlist)-1,func = Sort.isort,reverse = False)文件“ Sort.py “,第72行,按func(beg,end,reverse)排序,文件“ Sort.py”,第55行,在isort中键入self.numlist [beg + 1:end + 1]:#从beg + 1到结束AttributeError:“ int”对象没有属性“ numlist”

I am guessing if self is not first arguement then by default 'int' object is passed in isort. 我猜如果不是首先争论自己,那么默认情况下,“ int”对象将通过isort传递。 So its cribbing as int doesn't have attribute numlist. 因此,它作为int的特征没有numlist属性。

  1. Calling self.func(beg, end, reverse) never works no matter how I pass func in main. 无论我如何在main中传递func,调用self.func(beg,end,reverse)都行不通。 I tried func=Sort.isort and func=s.isort in main but everytime same attribute error saying 我在主要尝试过func = Sort.isort和func = s.isort但每次都出现相同的属性错误

AttributeError: 'Sort' object has no attribute 'func' AttributeError:“排序”对象没有属性“ func”

Could anyone please confirm my findings? 有人可以确认我的发现吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM