如何在python中调用父类方法?

时间:2018-03-30 06:03:57

标签: python class oop inheritance

我正在用python编写一个类。

class my_class(object):
    def __init__(self):
    # build my objects 
    def foo(self,*args,**kwargs):
    # do something with them

然后我想扩展这个课程:

class my_extended_class(my_class):

但我无法弄清楚访问父方法的正确方法是什么。

我可以:

1)创建父对象的实例?在构造函数时间

def __init__(self):
    self.my_father=my_class()
    # other child-specific statements
    return self
def foo(self,*args,**kwargs):
    self.my_father.foo(*args,**kwargs)
    # other child-specific statements
    return self

2)直接打电话给父亲方法'?

def foo(self,*args,**kwargs):
    my_class.foo(*args,**kwargs)
    # other child-specific statements
    return self

3)其他可能的方式?

2 个答案:

答案 0 :(得分:3)

使用$graphLookup

string playerName;
List<string> nameLibrary = new List<string> {"Tim", "Smithy", "Bill", "Max", "Ryan", "Johnathon", "Brisbane", "Pearly Whites", "Old Mate", "Shanequia", "Davo", "Ben", "Big Shaq", "John Cena", "King Thing", "Doug"};

void Start ()
{
    playerName = name;
    List<Player> myListOfPlayers = new List<Player>();

    for (int x = 0; x < 15; x++)
    {
        int randName = Random.Range(0, nameLibrary.Count);
        name = nameLibrary[randName];
        nameLibrary.Remove(name);

        Player somePlayer = new Player();
        somePlayer.Setup(name);
        myListOfPlayers.Add(somePlayer);
    }

    List<Player> team1 = new List<Player>();
    for (int i = 0; i <= 5; i++)
    {
        Player Player1 = new Player();
        team1.Add(myListOfPlayers[Random.Range(0, 15)]);
        myListOfPlayers.Remove(Player1);
    }

    // Display team 1
    Debug.Log ("Team 1");
    foreach (Player Player1 in team1) 
    {
        Player1.PrintLine();
    }

    List<Player> team2 = new List<Player>();
    for (int i = 0; i <= 5; i++)
    {
        Player Player2 = new Player();
        team2.Add (myListOfPlayers [Random.Range (0, 15)]);
        myListOfPlayers.Remove (Player2);
    }

    // Display team 2
    Debug.Log ("Team 2");
    foreach (Player Player2 in team2) 
    {
        Player2.PrintLine();
    }

How can I call super() so it's compatible in 2 and 3?中讨论了兼容性,但简而言之,Python 3支持在有或没有args的情况下调用super(ClassName, self),而Python 2则需要它们。

答案 1 :(得分:2)

您可以使用super()方法。例如:

class my_extended_class(my_class):
   def foo(self,*args,**kwargs):
      #Do your magic here 
      return super(my_extended_class, self).foo(self,*args,**kwargs)

您可以转到此链接并查找其他答案。

Call a parent class's method from child class in Python?