Python:在对象上传递和执行类方法

问题描述 投票:2回答:2

我有简单的类和对象

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

puss = Cat()

是否有像这样的机制的内置方法:

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

所以我可以分别传递和使用对象及其类函数?

我知道我可以:

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

和:

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

即使这样,解决我的问题但看起来很难看:

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

编辑:另一种方式是打电话:

 Cat.pet(puss)

但我的问题仍然是开放的:)

python python-3.x
2个回答
2
投票

没有比以下更简单的解决方案:

Cat.pet(puss)

为什么这样做?很简单,因为self和对象实例puss是内存中的同一个对象所以当你试图调用没有任何属性的Cat.pet()时,你会得到TypeError: pet() missing 1 required positional argument: 'self'所以你知道需要传递什么。现在你可以创建一个简单的函数:

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

添加argskwargs以保持将值传递给其他属性的可能性并使用它:

method_executor(Cat.pet, puss)

0
投票

我认为你的意思是miau而不是你的班级定义中的pet。然后你就可以做到

cat_sound = puss.miau
cat_sound()
© www.soinside.com 2019 - 2024. All rights reserved.