-2

Assuming I have class

class Class(object):
   @register_method_to_later_execution      
   @classmethod
   def my_class_method(cls):
   ... 

and @classmethod object. like this a = Class.my_class_method I need to be able to start executing it only if I having an a object. Is it possible to do that? and if possible - how It could be done?


The problem that I creating reference a at the moment of class creating (in decorator @register_method_to_later_execution for my_class_method) during the import

At that moment I just only have an object, and if I later trying to execute it, it throws class method is not callable

Ph0en1x
  • 9,943
  • 8
  • 48
  • 97

2 Answers2

2

Kinda trivial to test this yourself.

>>> class MyClass(object):
...     @classmethod
...     def my_class_method(cls):
...         print "hello world"
... 
>>> a = MyClass.my_class_method
>>> a
<bound method type.my_class_method of <class '__main__.MyClass'>>
>>> a()
hello world

Edit: If I understand you correctly from your edit (and I'm not at all sure that I do), it looks like you're trying to reference a class method before the class has actually been defined? That is not possible.

Use the @staticmethod decorator instead as that does not pass in the class variable as an argument.

Edit2: If you need the method to be a class method because you need access to the class variable for some reason, then you're out of luck and I would suggest rethinking your approach, as this one seems very strange to me and almost certainly isn't a good one :)

ptr
  • 3,292
  • 2
  • 24
  • 48
0

Just call it as you normaly would. Example:

In [1]: class Foo(object):
   ...:     @classmethod
   ...:     def my_method(cls):
   ...:         print('in my method')
   ...:

In [2]: foo = Foo()

In [3]: foo.my_method()
in my method

In [4]: Foo.my_method()
in my method

In [5]: method_reference = Foo.my_method

In [6]: method_reference()
in my method

In [7]:
del-boy
  • 3,556
  • 3
  • 26
  • 39
  • This isn't quite the same situation - the OP has a name referencing the class method itself, not an instance of the class – jonrsharpe Aug 18 '14 at 14:31
  • You are right, I missed that. I have edited example and added example that OP is looking for. – del-boy Aug 18 '14 at 17:34