0

I am wondering if it is possible to define a Python class with class variables initialized using a @classmethod of this class. Following code fails but explains what I mean:

class foo:
    a = 1
    b = 2
    c = foo.add(a, b)  # NameError: name 'foo' is not defined
    # c = a + b        # <-want to achieve this, but it duplicates add(), 
                       # which is what I want to avoid

    @classmethod
    def add(cls, x, y):
        return x+y

Also tried c = add(a, b) but got TypeError: 'classmethod' object is not callable.

Anybody has a clue? Any advice will be appreciated.

Cuteufo
  • 501
  • 6
  • 15
  • 1
    Does this answer your question? [How can I access a classmethod from inside a class in Python](https://stackoverflow.com/questions/13900515/how-can-i-access-a-classmethod-from-inside-a-class-in-python) – Chase Jul 17 '20 at 05:32
  • No, not in the class block. Well, you would have to do it after you define `add`, and since you decorated it with `classmethod`, you'd have to introspect the classmethod. Generally, this would be a dead end because a classmethod would generally rely on the class object (which doesn't exist yet when you are running the class definition statement), but since your classmethod doesn't need it, you can just pass `None` as the first argument... – juanpa.arrivillaga Jul 17 '20 at 05:40
  • it is failing there because you are trying to access a function that hasn't even been created at that point (following top-down structure). it's a different thing, if you declared `c = foo.add(a,b)` after the function is created. – de_classified Jul 17 '20 at 05:41
  • @FishingCode that would actually fail with a `TypeError`, since `classmethod` objects are not callable... but yes, you *could* do that with just a regular function. – juanpa.arrivillaga Jul 17 '20 at 05:46
  • The solution to this is *outside* the class definition, just do `foo.c = foo.add(foo.a, foo.b)` or whatever – juanpa.arrivillaga Jul 17 '20 at 05:47
  • @juanpa.arrivillaga agree with your last comment. but it wouldn't satisfy the OP question off getting it done within the `class foo`. – de_classified Jul 17 '20 at 05:54

0 Answers0