从没有参数的父类继承

时间:2017-03-26 13:50:06

标签: python python-2.7

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

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

代码:

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'

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

1 个答案:

答案 0 :(得分:0)

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

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._astring类之外的Vehicle,但应该将其视为一个错误。