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.

Josiah Yoder
  • 3,321
  • 4
  • 40
  • 58
  • 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. – Barmar Aug 02 '22 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. – Barmar Aug 02 '22 at 20:40
  • This is a bit too hypothetical to get at a real answer. Can you give us an exact use case? – C.Nivs Aug 02 '22 at 20:41
  • As I continued coding after writing this question, I found myself here: https://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. – Josiah Yoder Aug 02 '22 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. – chepner Aug 02 '22 at 20:47
  • @chepner Can you elaborate or link to an answer on that? The first answer [on this topic](https://stackoverflow.com/questions/136097/difference-between-staticmethod-and-classmethod) didn't explain this to me at all. – Josiah Yoder Aug 02 '22 at 20:49

2 Answers2

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.

Josiah Yoder
  • 3,321
  • 4
  • 40
  • 58
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.

chepner
  • 497,756
  • 71
  • 530
  • 681