1

I'm a beginner in Python and I am looking for a way to have a class with sub properties in it, so that I can group common properties together and have references to the main class. Example:

class RoadNetwork(object): # This is the main class
    def __init__(self):
        self.Types = ['Dirt', 'Gravel', 'Pavement']

    class HighWay(self): # This is the subclass
        def __init__(self):
            MaxSpeed = 55
            MinSpeed = 35
            Type = self.Types[2]


>>> roads = RoadNetwork()
>>> roads.Types
['Dirt', 'Gravel', 'Pavement']
>>> roads.HighWay.MaxSpeed
55
>>> roads.HighWay.MinSpeed
35
>>> roads.HighWay.Type
'Pavement'
>>>
4

2 回答 2

1

You got inheritance wrong. This is how you should declare a class hierarchy:

class RoadNetwork(object):  # This is the main class
    def __init__(self):
        self.types = ['Dirt', 'Gravel', 'Pavement']

class HighWay(RoadNetwork): # This is the subclass
    def __init__(self):
        RoadNetwork.__init__(self)
        self.maxSpeed = 55
        self.minSpeed = 35
        self.roadType = self.types[2]

For example:

road = RoadNetwork()
road.types
=> ['Dirt', 'Gravel', 'Pavement']

highway = HighWay()
highway.maxSpeed
=> 55
highway.minSpeed
=> 35
highway.roadType
=> 'Pavement'
于 2013-09-20T16:00:35.410 回答
0

I don't really think inheritance is what you are looking for, since a HighWay is a type of road but it is not a type of RoadNetwork. As far as I understand it, you just want a single instance of RoadNetwork and your types of roads would all have a reference to the same RoadNetwork instance.

I would also suggest moving some of your instance variables into class attributes. For example all instances of HighWay will have the same roadType so instead of assigning this at the instance level they would share the class value.

The simplest way to do this would probably be to just have all of your road types reference the global variable roads, but using global variables in this way is generally looked down upon. A better solution would be to use a class factory where you pass the reference to your RoadNetwork instance:

def highway_factory(roads):
    class HighWay(object):
        max_speed = 55
        min_speed = 35
        road_type = roads.types[2]
    return HighWay

class RoadNetwork(object):
    def __init__(self):
        self.types = ['Dirt', 'Gravel', 'Pavement']
        self.HighWay = highway_factory(self)

Example:

>>> roads = RoadNetwork()
>>> roads.types
['Dirt', 'Gravel', 'Pavement']
>>> roads.HighWay.max_speed
55
>>> roads.HighWay.min_speed
35
>>> roads.HighWay.road_type
'Pavement'
于 2013-09-20T16:15:44.430 回答