Python 2.6: Class inside a Class?

前端 未结 3 1753
小蘑菇
小蘑菇 2020-12-22 20:16

Hey everyone, my problem is that im trying to figure out how to get a class INSIDE another class.

What I am doing is I have a class for an Airplane with all its stat

3条回答
  •  不知归路
    2020-12-22 20:49

    It sounds like you are talking about aggregation. Each instance of your player class can contain zero or more instances of Airplane, which, in turn, can contain zero or more instances of Flight. You can implement this in Python using the built-in list type to save you naming variables with numbers.

    class Flight(object):
    
        def __init__(self, duration):
            self.duration = duration
    
    
    class Airplane(object):
    
        def __init__(self):
            self.flights = []
    
        def add_flight(self, duration):
            self.flights.append(Flight(duration))
    
    
    class Player(object):
    
        def __init__ (self, stock = 0, bank = 200000, fuel = 0, total_pax = 0):
            self.stock = stock
            self.bank = bank
            self.fuel = fuel
            self.total_pax = total_pax
            self.airplanes = []
    
    
        def add_planes(self):
            self.airplanes.append(Airplane())
    
    
    
    if __name__ == '__main__':
        player = Player()
        player.add_planes()
        player.airplanes[0].add_flight(5)
    

提交回复
热议问题