使用 Python 创建和实现接口?

Creating and Implementing an interface using Python?

我有两 (2) 个问题:首先,如何使用 Python 创建 FlyBehavior interface?其次,如何使用 Python implement FlyWithWings class 中的 FlyBehavior 接口(见下文)?我正在通过 Head First 学习设计模式,我想使用 Python

重写以下 Java classes
public abstract class Duck {

    // Reference variables for the 
    // behavior interface types
    FlyBehavior flyBehavior;
    QuackBehavior quackBehavior;

    public Duck() {
    }

    // Delegate to the behavior class
    public void performFly(){
        flyBehavior.fly();
    }

    // Delegate to the behavior class
    public void performQuack(){
        quackBehavior.quack();
    }
}

这里是所有飞行行为class实现的接口

public interface FlyBehavior {
    public void fly();
}

这是会飞的鸭子的飞行行为实现

public class FlyWithWings implements FlyBehavior {
    public void fly(){
    System.out.println("I'm flying");
    }
}

这是我目前使用的 Python。下面是我的Python摘鸭class

import abc

class Duck:
    __metaclass__=abc.ABCMeta


    FlyBehavior FlyBehavior;
    QuackBehavior QuackBehavior;

    @abc.abstractmethod
    def __init__():
        return

    @abc.abstractmethod
    def performFly():
        return

    @abc.abstractmethod
    def performQuack():
        return

这是我在尝试创建界面和尝试实现界面时卡住的地方。

Python 是一种 duck typed 语言。你不需要接口——你传入一个对象,如果它支持你想要的方法,它就可以工作。如果它没有它爆炸的方法。它没有 Java 具有的编译时检查。如果需要检查,请在 运行 时间自行检查。所以它应该只是:

import abc

class Duck:
    __metaclass__=abc.ABCMeta


    FlyBehavior FlyBehavior;
    QuackBehavior QuackBehavior;

    @abc.abstractmethod
    def __init__():
        return

    @abc.abstractmethod
    def performFly():
        flyBehavior.fly()

    @abc.abstractmethod
    def performQuack():
        quackBehavior.quack()

更广泛地说,并非所有设计模式都适用于所有语言。参见 Are Design Patterns Missing Language Features

正如 Alex Taylor 所指出的,Python 是一种鸭子类型的语言——你不需要指定事物的类型,你只需使用它们。

不过,我认为他翻译的Java代码是错误的。您不需要在这里使用 abc - 只需使用正常的 class.

class Duck(object):
    # Like in Java, you don't need to write a __init__ if it's empty

    # You don't need to declare fields either - just use them.

    def performFly(self):
        self.flyBehaviour.fly()

    def performQuack(self):
        self.quackBehaviour.quack()

class FlyWithWings(object):
    def fly(self):
        print "I'm flying"

# Example:
d = Duck()
d.flyBehaviour = FlyWithWings()
d.performFly() # prints "I'm flying"