【问题标题】:Class Inheritance for python 2.7python 2.7的类继承
【发布时间】:2018-01-23 17:48:31
【问题描述】:

我需要让子类从超类 Vehicle 中获取信息并进入它们相应的类并携带信息。但是我不能让他们延续到新的班级。我需要做什么才能允许继承特定特征?

class Vehicle:
    def __init__(self, make , model):
        self.year = 2000
        self.make = make
        self.model = model
# a vehicle is instantiated with a make and model
    @property
    def year(self):
        return self._year

    print "year"
#mutator
    @year.setter
    def year(self, value):
        if (value >= 2000):
            self._year = value
        if (value <= 2018):
            self._year = value
        if (value > 2018):
            self.value = 2018
        else:
            self._year = 2000
    pass

class Truck(Vehicle):
    pass

class Car(Vehicle):
    pass

class DodgeRam(Truck):
    pass

class HondaCivic(Car):
    pass

ram = DodgeRam(2016)
print ram

civic1 = HondaCivic(2007)
print civic1

civic2 = HondaCivic(1999)
print civic2

【问题讨论】:

  • 请发布您到目前为止所尝试的内容。
  • 什么,确切地,不起作用?
  • 注意,你不小心做了self.value = 2018而不是self._year = 2018
  • 我不能让汽车/卡车继承那一年,然后去道奇拉姆/本田思域
  • 我真正需要知道的是如何从另一个类继承一些东西

标签: python python-2.7


【解决方案1】:

根据您的评论,“我真正需要知道的是如何从另一个类继承某些东西”

class Vehicle():
    def __init__(self):
        self.year = 2000

class Truck(Vehicle):
    pass

class DodgeRam(Truck):
    pass

print(DodgeRam().year)

这对我来说很好。年份的继承是自动的,Python2 和 Python3 都打印了 2000。

您的问题似乎是您在单个汽车创建级别输入年份输入,但正试图在超级级别存储该值。您应该将值存储在它们共享的最低级别:

class Vehicle():
    pass

class Car(Vehicle):
    def __init__(self):
        self.wheels = 4

class HondaCivic(year):
    def __init__(self, year):
        self.make = 'Honda'
        self.model = 'Civic'
        self.year = year

如果您想强制子类具有某些值(品牌/型号)而不是将它们留空,您可以查看Enforcing Class Variables in a Subclass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 2016-06-27
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    相关资源
    最近更新 更多