Vinny Banks
Vinny Banks

Reputation: 23

Calling parent class in python

My issue here is with calling classes inside another class. Independently, I can set this up how I want the 2 classes to work. I just cannot get them working together. I want my dataset (which is football fixtures and results) to be passed to a class League, which holds all the league info and then every team inside that league is inside the class Team which is a child of the parent class League. Example shows just a snippet of how this is set up

At the bottom of the example you will see the function 'total_attack_strength_home(self):' Here I need to access the class Team, but then the last part of the calculation references the respective class object (The league that the club sits in). Any help on this would be appreciated. Thanks

'''

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'''

Upvotes: 0

Views: 66

Answers (2)

SamudNeb
SamudNeb

Reputation: 221

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).

Upvotes: 1

Alejandro Kaspar
Alejandro Kaspar

Reputation: 464

I think your class League should be abstract (delegating the implementation to the subclasses).

Like:

import abc
class League(metaclass=abc.ABCMeta):
    ....

    @abc.abstractmethod
    def get_total_goals_scored(self):
        pass

Then you'll need to implement it on your Team class.

In addition to what's already commented (considering using composition rather than inheritance) and missing to invoke the parent constructor on your child class

Upvotes: 0

Related Questions