0

I know this is probably not a good style, but I was wondering if it is possible to construct a class when a static method is called

class myClass():
    def __init__(self):
        self.variable = "this worked"

    @staticmethod
    def test_class(var=myClass().variable):
        print self.variable


if "__name__" == "__main__":
    myClass.test_class()

Right now it returns

NameError: name 'myClass' is not defined

Here is what I am suspecting, in default, the python interpreter will scan the class and register each function, when it register the function, it checks the function's default variable, the default variable have to be defined?

Kevin
  • 83
  • 2
  • 6

2 Answers2

2

Perhaps the easiest is to turn it into a classmethod instead:

class myClass(object):

    def __init__(self):
        self.variable = "this worked"

    @classmethod
    def test_class(cls):
        var = cls().variable
        print var

if __name__ == "__main__":
    myClass.test_class()

See What is the difference between @staticmethod and @classmethod in Python?

It is not entirely clear from your question what the use case is; it could well be that there's a better way to do what you're actually trying to do.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Yes, the default value for a function argument has to be definable at the point that the function appears, and a class isn't actually finished defining until the end of the "class block." The easiest way to do what you're trying to do is:

@staticmethod
def test_class(var=None):
    if var is None: var = myClass().variable
    print var  # I assume this is what you meant to write for this line; otherwise, the function makes no sense.

This has the one downside that you can't pass None to myClass.test_class and get it to print out. If you want to do this, try:

@staticmethod
def test_class(*vars):
     if len(vars) == 0:
         var = myClass().variable
     #elif len(vars) > 1:
         # Throw an error yelling at the user for calling the function wrong (optional)
     else:
         var = vars[0]
     print var
jwodder
  • 54,758
  • 12
  • 108
  • 124