Python class methods: when is self not needed

前端 未结 4 450
别跟我提以往
别跟我提以往 2020-12-30 13:19

I\'m trying to rewrite some code using classes. At some point what I want is assign a member function a particular definition using a parameter value for each instance of an

4条回答
  •  生来不讨喜
    2020-12-30 14:02

    I think what has confused you here is that you're accessing the method via the class attribute activationFunctions, rather than (as an instance would normally be accessed) on the instance itself. For example, given:

    class Class:
    
        def method(self, foo, bar):
            print(self, foo, bar)
    
        methods = {'method': method}
    

    When we call the method directly from the dictionary:

    >>> Class.methods['method'](1, 2, 3)
    1 2 3
    

    You can see that we're passing 1 as the self parameter; the method isn't being called on an instance, so no instance is being injected. By contrast, when we call it on an instance:

    >>> instance = Class()
    >>> instance.method(1, 2)
    <__main__.Class object at 0x...> 1 2
    

    Now our arguments are foo and bar, and the instance is self. That's why you think a different number of parameters seem to be required.


    In this case, as you don't actually need the instance state in your method, just make it a regular function (note minor revisions for PEP-8 compliance):

    def non_linear_bipolar_step(x, string=None):
        if string is not None: 
            return -1 if x < 0 else 1
        return '-' if x < 0 else '1'
    
    class Activation:
    
        activation_functions = {
            'bipolar': non_linear_bipolar_step,
        }
    
        ...
    

    This is likely less confusing.

提交回复
热议问题