我如何在Python中运行抽象方法(子将实现它)和抽象hirrachy

时间:2014-02-13 14:54:31

标签: python polymorphism abstract-class

我是Python的新手,我想将Java项目转换为Python,这是我在Java中的代码的基本示例:(我真的想知道如何在Python中使用抽象类和多态) / p>

public abstract class AbstractGrandFather {

   protected ArrayList list = new ArrayList();

   protected AbstractGrandFather(){
          list.add(getGrandFatherName());
   }

   protected abstract String getGrandFatherName();

}

public abstract class AbstractParent extends AbstractGrandfather {

   protected AbstractParent(String name){
          super();
          list.add(name);
}

public class Child extends AbstractParent {

   public Child(String fatherName, String childName){
          super(fatherName);
          list.add(childName);
   }

   public String getGrandFatherName(){
          return "Samuel";
   }
}

这是我在Python中尝试做的事情:

import abc
from abc import ABCMeta, abstractmethod

class AbstractGrandFather(object):
    __metaclass__ = ABCMeta

    @abc.abstractmethod
    def __init__(self):
        list = [self.get_command_name(self)]

    @abc.abstractmethod
    def get_command_name(self):
        pass

    @property
    def get_list(self):
        return self.list

class AbstractParent(AbstractGrandFather):
    __metaclass__ = ABCMeta

    @abc.abstractmethod
    def __init__(self, name):
        self.list = super.get_list.append(name)

    @abc.abstractmethod
    def get_command_name(self):
        pass

class Child(AbstractParent):
    def get_command_name(self):
        return "Samuel"

    def __init__(self, father_name, child_name):
        self.list = super(father_name).get_list.append(child_name)


x = Child("Dan," "Ben")

但它不起作用我收到错误:

Traceback (most recent call last):
  File "Dummy.py", line 43, in <module>
    x = Child("Dan," "Ben")
TypeError: __init__() takes exactly 3 arguments (2 given)

我是否在正确的轨道上?将会感谢一些帮助和指导。

谢谢

1 个答案:

答案 0 :(得分:1)

编辑:修复了multipython兼容性 Edit2:最后添加了一些指示......

看看这个:

class AbstractGrandFather(object):
    __metaclass__ = ABCMeta

    @abc.abstractmethod
    def __init__(self):
        self._list = [self.get_command_name()]

    @abc.abstractmethod
    def get_command_name(self):
        pass

    @property
    def list(self):
        return self._list


class AbstractParent(AbstractGrandFather):
    __metaclass__ = ABCMeta

    @abc.abstractmethod
    def __init__(self, name):
        super(AbstractParent, self).__init__()
        self.list.append(name)

    @abc.abstractmethod
    def get_command_name(self):
        pass


class Child(AbstractParent):
    def get_command_name(self):
        return "Samuel"

    def __init__(self, father_name, child_name):
        super(Child, self).__init__(father_name)
        self.list.append(child_name)

在Python 3上super()就够了,不需要super(class, instance)

您可能需要阅读关于super的{​​{3}}。