Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中对_str__方法调用super()?_Python_String_Python 3.x_Class - Fatal编程技术网

在python中对_str__方法调用super()?

在python中对_str__方法调用super()?,python,string,python-3.x,class,Python,String,Python 3.x,Class,我已经玩OOP好几天了,现在我想了解super()方法是如何工作的 我遇到的问题是,我想从另一个类调用我的\uuu str\uu函数,并继承超类中的内容 我读过,但那个解决方案不起作用 我的密码是这样的 class Taxi: def __init__(self, drivername, onduty, cities): self.drivername = drivername self.onduty = onduty self.citi

我已经玩OOP好几天了,现在我想了解
super()
方法是如何工作的

我遇到的问题是,我想从另一个类调用我的
\uuu str\uu
函数,并继承超类中的内容

我读过,但那个解决方案不起作用

我的密码是这样的

class Taxi:

    def __init__(self, drivername, onduty, cities):
        self.drivername = drivername
        self.onduty = onduty
        self.cities = cities

    def __str__(self):
        return '{} {} {}'.format(self.drivername, self.onduty, self.cities)

class Type(Taxi):

    def __init__(self, drivername, onduty, cities, model):
        super().__init__(drivername, onduty, cities)
        self.model = model

    def __str__(self):
        super(Taxi, self).__str__() #Tried as well with super().__str__()
        return '{}'.format(self.model)

mymodel = Type('Foobar', True, 'Washington', 'Volvo')
print(mymodel)
因此,我希望Taxi类中的
\uuuu str\uuu
函数返回给定的值,然后子类中的string类返回最后一个值


我该怎么做?

您完全忽略了调用
\uuu str\uu
的超类定义的结果。你可能想要一些类似的东西

def __str__(self):
    prefix = super().__str__()
    return '{} {}'.format(prefix, self.model)

调用
super()。\uuuu str\uuuuu()
并没有任何神奇的作用。这只是另一个方法调用,所以您需要这样对待它。除非您这样做,否则返回值将不会神奇地吸收到您的方法中。

super(Taxi,self)。\uu str\uu()
返回一个您完全忽略的字符串。你不能就这么说,你需要对结果做点什么,正如你在另一篇文章中所说的那样,没有帮助。我不知道你为什么会被否决。这是一个很清楚的问题,不管多么简单,你显然自己也花了一些精力去解决它。@MadPhysicast:同意。许多教程仅显示调用
super()。\uuuu init\uuuu(…)
的示例,它没有返回值。所以这种混乱是完全可以理解的。