首页 > 解决方案 > 在python中调用父类

问题描述

我的问题是在另一个类中调用类。独立地,我可以设置这两个类的工作方式。我就是不能让他们一起工作。我希望将我的数据集(即足球赛程和结果)传递给一个包含所有联赛信息的类 League,然后该联盟中的每个团队都在类 Team 中,该类是父类 League 的子类。示例仅显示了如何设置的片段

在示例的底部,您将看到函数 'total_attack_strength_home(self):' 在这里我需要访问类 Team,但计算的最后一部分引用了相应的类对象(俱乐部所在的联赛)。对此的任何帮助将不胜感激。谢谢

'''

class League(): 
    def init(self,league): 
        self.league = league 
        self.total_goals_scored = self.get_total_goals_scored() 
        self.home_goals_scored = self.get_home_goals_scored()
    def get_total_goals_scored(self):
        pass
    def get_home_goals_scored(self):
        pass


class Team(League): 
    def init(self,club): 
    self.club = club 
    self.home_wins = self.get_home_wins() 
    self.home_draws = self.get_home_draws()

    def total_attack_strength(self):
        if len(self.total_goals) == 0:
            attack_strength = 0
        else:
            attack_strength = (sum(self.total_goals) / len(self.total_goals)) / ***(total_goals_scored/games_played)***
        return attack_strength'''

标签: pythonclassoop

解决方案


There are a few variables that don’t seem to be defined anywhere, so I’m assuming this Is just a snippet example.

As mentioned, use super when you want parent class code to run. So in the child’s init, throw a super().__init__() to get the parent’s init running. If you’re just trying to access the parents attributes, remember you inherited those. So a self.foo will get either your or your parents definition of foo automatically, whichever happened last (which will be the child’s in most cases).


推荐阅读