Python Forum

Full Version: how to make class and instance method (multiple decorator) ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want make a method like in the following example

class foo():
   
   @classmethod
   @instancemethod # problem:NameError: name 'instancemethod' is not defined
   def method(cls, self):
        print("method class =", cls)
        print("method object =", self)

example = foo()
example.method()
#___output___
# method class = .......
# method object = .....
how can I make it in other way ?

Thanks
That doesn't really make sense. You can't call it as a class method, since you won't know the instance. Calling it as an instance method, you can get cls with type(self). So why both?

Also, in Python we almost never use class methods. Why not just a regular function?
If you really want this for some reason, you could do something like this
class Foo():
    def __init__(self):
        self.method = self.__instance_method
    
    @classmethod
    def method(cls):
        print("method class =", cls)

    def __instance_method(self):
        print("method object =", self)
 
Foo.method()

foo = Foo()
foo.method()
Output:
method class = <class '__main__.Foo'> method object = <__main__.Foo object at 0x7f76cb5409e8>
But again, making their behavior identical doesn't really make sense.
@micseydel,

thanks.
Could you elaborate on why you need this?
@micseydel,

import os, sys

import langauge.main

__filepath__ = os.path.realpath(__file__)
__directory__ = os.path.dirname(__filepath__)
__progdir__ = os.path.dirname(__directory__)


class main():
	launched = False
	def __init__(self):
		pass

	@classmethod
	def run(cls, self):
		if cls.launched:
		    pass




if __name__ == "__main__":
	program = main()
	program.run()

	del program.run  # this code for prevent the running again program
You can achieve the same thing using the techniques shown above:

class Main(object):

    launched = False

    def run(self):
        if not self.launched:
            print('Running...')
            type(self).launched = True
        else:
            raise RuntimeError('Program has already been run.')
Output:
>>> x = Main() >>> y = Main() >>> x.run() Running... >>> y.run() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "forum_test.py", line 10, in run raise RuntimeError('Program has already been run.') RuntimeError: Program has already been run.
@ichabod801,

Thanks.