pbaranski
pbaranski

Reputation: 24962

Python: Passing and executing class method on object

I have simple class and object

class Cat():
    def pet(self):
        print('mrrrrrr')

puss = Cat()

Is there a builtin method for mechanism like this:

cat_sound = ???(puss, Cat.pet)

So I can separately pass and use object and its class function in nice way?

And I know that I can:

cat_sound = getattr(puss, 'pet')
cat_sound()

And:

 catsound = getattr(puss, Cat.pet.__name__)
 catsound()

Even this way what solves my problem but looks ugly:

 catsound = getattr(puss, getattr(Cat.pet, '__name__'))
 catsound()

EDIT: The another way is to call:

 Cat.pet(puss)

But my question is still open :)

Upvotes: 2

Views: 81

Answers (2)

maQ
maQ

Reputation: 506

There is no simpler solution than:

Cat.pet(puss)

Why does this work? Simple because self and object instance puss is the same object in the memory so when you will try to call Cat.pet() without any attribute, you will get TypeError: pet() missing 1 required positional argument: 'self' so you know what needs to be passed. Now you can create a simple function like that:

def method_executor(method_ref, obj_instance, *args, **kwargs):
    return method_ref(obj_instance, *args, **kwargs)

args and kwargs are added to maintain possibility passing values to other attributes and use it like that:

method_executor(Cat.pet, puss)

Upvotes: 2

Philipp F
Philipp F

Reputation: 427

I think you mean miau instead of pet in your class definition. Then you can simply do

cat_sound = puss.miau
cat_sound()

Upvotes: 0

Related Questions