繁体   English   中英

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

[英]how can i run an abstract method in Python (child will implement it) and abstract hirrachy

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

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)

我在正确的轨道上吗? 将不胜感激一些帮助和指导方针。

谢谢

编辑:修复多Python兼容性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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM