Define a method outside of class definition?

前端 未结 4 453
天命终不由人
天命终不由人 2020-11-30 00:01
class MyClass:
    def myFunc(self):
        pass

Can I create MyFunc() outside of the class definition, maybe even in another module?

4条回答
  •  佛祖请我去吃肉
    2020-11-30 00:17

    You can define a function outside of a class and then add it. However, there is a subtle difference in assigning the function to the class or to the instance object. Here is an example:

    class MyClass1(object):
        def __init__(self, bar):
            self.foo = 'up'
            MyClass1.foobar = bar
    
    class MyClass2(object):
        def __init__(self, bar):
            self.foo = 'up'
            self.foobar = bar
    
    def bar(self):
        return "What's " + self.foo
    

    Let's first look at what is happening in MyClass1. foobar in this class is similar to a normal method as though it was defined inside the class definition (i.e. it is a method bound to the instance of this class). Let's take a look at what this looks like...

    In [2]: x = MyClass1(bar)
    
    In [3]: x.foobar
    Out[3]: >
    
    In [4]: x.foobar()
    Out[4]: "What's up"
    

    How does this differ from MyClass2? In MyClass2, foobar is simply a reference to the bar function and is NOT a bound method. Because of this we must pass the instance in for this function to work properly. e.g.

    In [5]: y = MyClass2(bar)
    
    In [6]: y.foobar
    Out[6]: 
    
    In [7]: y.foobar()
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
     in ()
    ----> 1 y.foobar()
    
    TypeError: bar() takes exactly 1 argument (0 given)
    
    In [8]: y.foobar(y)
    Out[8]: "What's up"
    

    Although I'm not sure if this is ever good practice to be doing it this way...

提交回复
热议问题