Default variable referencing native class in python

I am trying to write something like:

class MyClass(object):
    @staticmethod
    def test(x, y, z=None):
        if not z:
            z = external_function(MyClass)

Is it possible in python to rewrite it to something like:

class MyClass(object):
    @staticmethod
    def test(x, y, z=external_function(MyClass)):
        pass

(The second code does not work because it refers to MyClass, which is not defined at this point)

+3
source share
2 answers

It is not possible to rewrite the code in this way. The closest you can do is something like:

class MyClass:
      pass

def test(x, y, z=external_function(MyClass):
      pass

MyClass.test = staticmethod(test)
del test

Note that this assumes Python 3; in Python 2, you may need to work with a module new. But, although it is possible, the intent of the code is very unobvious. It’s best to stick with if z is Noneor reorganize your code so that it does not need it.

+3
source

, , , , , , , . , .

def say_hi():
    print "Getting default value"

class MyClass(object):
    print "Creating class"
    @staticmethod
    def test(a=say_hi()):
        print "test called"

MyClass.test()
MyClass.test()

:

Creating class
Getting default value
test called
test called
+3

All Articles