Python-以结构化方式向类动态添加新功能

时间:2018-12-17 12:31:48

标签: python python-3.x class inheritance structure

我有一个基本类,其中存储了一些变量和对象,如:

class Human():
    arms = Arms()
    legs = Legs()
    head = Head()

,我也想动态地向此类添加函数。例如:

class Swim():
    def moveArms(self):
        self.arms related stuff

    def breathe(self):
        self.head related stuff

然后在此示例中,我想将此Swim类提供给人类,以便像learnSwim这样的函数可以将这些函数传递给Human类或任何其他任意类,例如Dog等等,只要它们具有ArmsHead

但是如果我有一个这样的类与我的初始类不兼容,如下所示:

class Fly():
    def flapWings:
       do stuff with self.wings()

,我尝试将此类传递给Human,我希望它在评估中不兼容。像learnFly(human_instance)应该失败,因为Human没有翅膀。它不应该传递flapWings函数,而Human仅意识到在调用函数时不会起作用。

我想我可以做到:

def learnSwim(instance):
    if instance.arms is not None and instance.head is not None:
         instance.moveArms = Swim.moveArms
         instance.breathe = Swim.breathe
    else:
         raise Exception("No arms or head! I guess I'll just drown")

def learnFly(instance):
    if instance.wings is not None:
         instance.flapWings = Fly.flapWings
    else:
         raise Exception("Have no wings but you never know!")

所以我的问题是,有没有更多的本机/ pythonic /简单/常规方式来实现这一目标?

0 个答案:

没有答案