gpt4 book ai didi

具有子属性的 Python 类(初学者)

转载 作者:太空宇宙 更新时间:2023-11-03 18:48:31 25 4
gpt4 key购买 nike

我是Python的初学者,我正在寻找一种方法来拥有一个包含子属性的类,以便我可以将公共(public)属性组合在一起并引用主类。示例:

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

最佳答案

你的继承错误。这是声明类层次结构的方式:

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]

例如:

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

highway = HighWay()
highway.maxSpeed
=> 55
highway.minSpeed
=> 35
highway.roadType
=> 'Pavement'

关于具有子属性的 Python 类(初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18920955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com