mardi 24 novembre 2020

In python3, what's the difference between defining a class method inside or outside __init__ function?

Example

class Foo:
    def __init__(self, val):
        self.val = val
    def f(self,arg=None):
        if arg: print(arg)
        else: print(self.val)
    @classmethod
    def otherclassmethods(cls):pass

class Foo2:
    def __init__(self, val):
        # self.val = val, no need that
        def f(arg=val):
            print(arg)
        self.f = f
    @classmethod
    def otherclassmethods(cls):pass

I found it's perfect to define a class method inside __init__ function:

  1. in the normal class method I don't need self argument anymore.
  2. I don't need setattr to Foo2, and it's encapsulated automatically.
  3. Function looks more similar to c++.

If I define all class members inside __init__ function, and I am more concerned with their real practical effect. Maybe in concept, a closure inside __init__ is not a class method, but I think it work well as a classmethod. Based on it my question is: what's the difference between defining a class method inside or outside __init__ function?

Please help me.

Aucun commentaire:

Enregistrer un commentaire