1

Is it possible to have a function that not only behaves like a @staticmethod wrapped function but also like any other class function so that if one calls the function through an instance, the data from the instance can be passed?

example:

class Amazing(object):
    @static_and_class
    def func(x):
        return type(x)

apple = Amazing()

>>> print(apple.func())
>>> <class 'Amazing'>
>>> print(Amazing.func(2))
>>> <class 'int'>

That's a basic example of the system. Basically, what I want is a way to pass information like instance data if possible, but if the data was not there the function would take the necessary variables to execute its program.

Thanks to anyone who can solve this!!

1
  • There's no built-in function for this, but you can easily write such decorator. Commented Mar 29, 2015 at 21:04

1 Answer 1

1

Any method of any class can be called through the class' name. An instance will automatically pass itself as the first parameter of any of its methods. So, if you have something like

class Bar:
    def bar(self):
        return type(self)

you can do

thing = Bar()
print(thing.bar())
print(Bar.bar(2))

and you will get

<class '__main__.Bar'>
<class 'int'>

with no problems. This is, of course, frowned upon; when writing methods for instances, the method should be written such that self is presumed to be an instance of the class it is written for.

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

3 Comments

Well that's only true for Python 3 where they removed the concept of un-bound methods.
but my code has parts like self.foo where a self argument wouldn't work for non-instances
You could use type-checking to take care of that, if you wanted to; split the behavior depending on whether or not the argument is an instance of the class.

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.