Home > OS >  Is there a class-and-instance method in Python?
Is there a class-and-instance method in Python?

Time:08-03

Is there a way of creating a method with this signature?

def(self, cls, arg1, arg2, arg3):
    self.instance = cls.some_class_default

I'm aware of instance methods:

def(self, arg1, arg2):
   self.instance = some_default_literal_value

and class methods:

@classmethod
def(cls, arg1, arg2)
   cls.some_class_default = arg1

But is there a conventional way to mark a method that uses both instance variables and class variables?

Even within a method, self.__class__.some_class_default feels cumbersome, so such a method feels like it could be valuable.

CodePudding user response:

The convention is to access the class variables directly through the self reference, e.g.:

def(self, arg1, arg2, arg3):
    print(self.some_class_default)

The advantage of this approach is that you don't need to change the method signature just to access a class variable from an instance method.

CodePudding user response:

Getting the class is trivial:

def foo(self, x, y, z):
    cls = type(self)
    ...

Adding an entire other kind of method to do this automatically

class Foo
    @combomethod
    def bar(self, cls, x, y, z):
        ...

seems like it would have minimal benefit.

  • Related