0

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.

6
  • It sounds like a decorator you could easily write yourself. I don't think this is something that's needed often enough for there to be a standard decorator. Commented Aug 2, 2022 at 20:38
  • 1
    Why do you need this? In OOP, it's rare to need to refer to the instance's class directly, as that's likely to bypass inheritance. Commented Aug 2, 2022 at 20:40
  • This is a bit too hypothetical to get at a real answer. Can you give us an exact use case? Commented Aug 2, 2022 at 20:41
  • As I continued coding after writing this question, I found myself here: stackoverflow.com/a/15189304/1048186 I think that the problem was that I was trying to access a class variable within the default parameters of a method. Commented Aug 2, 2022 at 20:42
  • You can always get cls with type(self); I don't seen any benefit to having a specific method that automatically gets passed both. The main point of a class method is not so much that the class is passed automatically as the fact that the class is passed whether you invoke the method from the class or from an instance of the class. Commented Aug 2, 2022 at 20:47

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.