【问题标题】:Inheritance from a parent class without arguments从没有参数的父类继承
【发布时间】:2017-03-26 13:50:05
【问题描述】:

我有两节课。一个车辆类和一个汽车类。我的车辆类没有任何属性,所以我可以在没有任何参数的情况下调用它。我的汽车课也一样。汽车类是车辆类的子类。

在我的车辆类中,我有一个变量分配了一个带有一些文本的字符串。我的子类车怎么能继承那个变量呢?

代码:

class Vehicle(object):
    def __init__(self):
        self.__astring = 'Hello'

    def get_string(self):
        print self.__astring


class Car(Vehicle):
    def __init__(self):
        Vehicle.__init__(self)
        # Here I need to make a working variable
        self.__car_string = self.__astring
        self.__car_string2 = ' Again'
        self.__big_string = self.__car_string + self.__car_string2

    # This method should print 'Hello Agan'
    def get_car_string(self):
        print self.__big_string


string1 = Vehicle()
string1.get_string()    # This prints Hello

string2 = Car()
string2.get_car_string()    # This should print Hello Again

当我运行代码时,我得到:

AttributeError: 'Car' object has no attribute '_Car__astring'

我明白为什么,但我不知道如何用字符串继承那个变量。

【问题讨论】:

  • 如果希望子类能够访问该属性,为什么用__double_leading_underscores命名呢?名称修改的全部目的是避免冲突,因此您可以在子项和父项中使用相同的名称。这与是否有 __init__ 参数无关。另外你为什么不使用super
  • 我认为隐藏/私有属性是在 Python 中编码的正确方法。所以这使得属性只能从对象方法中访问。所以你说这是问题所在?
  • @nutgut 阅读this
  • 嗯:1. 不,它不是,我们都是在这里同意的成年人,在 Python 中没有什么是真正私有的/受保护的; 2. 如果您确实想按照约定将其设为私有,则为_single_leading_underscore 而不是__double; 3. 是的,这就是问题所在。
  • 在编写 Python 时不要担心 public/protected/private。见stackoverflow.com/q/17246867/7432stackoverflow.com/q/1641219/7432

标签: python python-2.7


【解决方案1】:

将属性标记为私有的正确方法(意味着它不应该直接在该类的方法之外使用,而不是它不能)是用一个下划线作为前缀。

getter 方法应该返回 值,而不是打印它。如果需要打印值,可以随时打印get_string的返回值;您不能(轻松)访问由方法直接打印的值。

class Vehicle(object):
    def __init__(self):
        self._astring = 'Hello'

    def get_a_string(self):
        return self._astring


class Car(Vehicle):
    def __init__(self):
        Vehicle.__init__(self)
        # Here I need to make a working variable
        self._car_string = self.get_a_string()
        self._car_string2 = ' Again'
        self._big_string = self._car_string + self._car_string2

    def get_car_string(self):
        print self._big_string

语言本身不会阻止您直接在Vehicle 类之外访问Vehicle._astring,但这样做应该被视为一个错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 2020-02-09
    • 2015-11-25
    • 2014-09-09
    • 2019-02-28
    • 2017-03-18
    • 2020-10-30
    相关资源
    最近更新 更多