3

I'm 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 as it is referencing MyClass which is not defined at this point)

3
  • 1
    Class methods must have the instance variable (object) self as their first variable. 99% of the time, you're not passing the class to an external function, you're passing the instance variable (or object), self, to the external function. What you're doing with the class as a whole, seems incorrect. Are you trying to write a @classfunction? Or are you trying to manipulate an object of the class? Commented Jun 3, 2011 at 10:11
  • It's actually @staticmethod. Commented Jun 3, 2011 at 10:19
  • 1
    Not a fix for your problem, but you should really make test a classmethod, which takes cls as the first parameter, then use that in your call to external_function. Commented Jun 3, 2011 at 10:48

2 Answers 2

3

It is not possible to rewrite the code that 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 fiddle around with the new module. But though this is possible, the intention of the code is very non-obvious. It is better to stick to if z is None, or to refactor your code to not need this.

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

1 Comment

Unfortunately it is python 2 (2.5 or 2.6)
3

It's not possible, since whatever is in the argument definition of any method, be it a static method or a normal method, is parsed and executed at class creation time, before the class object that you try to use has been created. Defaults are also evaluated at this time, as the code below demonstrates.

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()

Output:

Creating class
Getting default value
test called
test called

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.