【问题标题】:Inheritance in derived class not called未调用派生类中的继承
【发布时间】:2020-10-20 10:10:24
【问题描述】:

我是这个堆栈溢出的新手,这是我在这里的第一个问题。 我正在学习 python,但我遇到了继承问题。我认为我的代码是正确的,但它没有从派生/子类继承父/基类。我尝试了两种继承方式。它正在打印 Normalphones 类的全名,但不是 Smartphones。我的代码在这里。帮帮我。

class Normalphones:  # base class/ parent class
    def __init__(self, brand, model_name, price):
        self.brand = brand
        self.model_name = model_name
        self._price = max(price, 0)


    def full_name(self):
        return f"{self.brand} {self.model_name}"
    
    
    def make_a_call(self, number):
        return f"Calling {number} ...."


class Smartphones:  # derived class / child class
    def __init__(self, brand, model_name, price, ram, internal_memory, rear_camera):
        Normalphones.__init__(self, brand, model_name, price)  # uncommom way to inherit
        # super().__init__(brand, model_name, price)
        self.ram = ram
        self.internal_memory = internal_memory
        self.rear_camera = rear_camera


noramalphone1 = Normalphones('Nokia', '1150', 1200)
smartphone1 = Smartphones('I-phone', '11 max pro', 90000, '6 Gb', '128 Gb', '48 MP')

print(noramalphone1.full_name())
print(smartphone1.full_name())

【问题讨论】:

  • 应该是class Smartphones(Normalphones): ...
  • 您究竟希望 Python 如何知道 Smartphones 应该是 Normalphones 的派生类?

标签: python class inheritance derived-class python-class


【解决方案1】:

这是你继承的方式:类 Smartphones(Normalphones):

class Normalphones:  # base class/ parent class

    def __init__(self, brand, model_name, price):
        self.brand = brand
        self.model_name = model_name
        self._price = max(price, 0)

    def full_name(self):
        return f"{self.brand} {self.model_name}"

    def make_a_call(self, number):
        return f"Calling {number} ...."


class Smartphones(Normalphones):  # derived class / child class
    def __init__(self, brand, model_name, price, ram, internal_memory, rear_camera):
        super().__init__(brand, model_name, price)
        self.ram = ram
        self.internal_memory = internal_memory
        self.rear_camera = rear_camera


noramalphone1 = Normalphones('Nokia', '1150', 1200)
smartphone1 = Smartphones('I-phone', '11 max pro',
                          90000, '6 Gb', '128 Gb', '48 MP')

print(noramalphone1.full_name())
print(smartphone1.full_name())

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 2011-01-08
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    相关资源
    最近更新 更多