我已经玩了几天OOP,现在我正在努力了解该super()方法的工作原理.
我遇到的问题是我想__str__从另一个类调用我的函数并继承超类中的东西.
我读了Python继承:与super __str__连接,但该解决方案不起作用.
我的代码就是这个
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)
Run Code Online (Sandbox Code Playgroud)
所以我希望__str__Taxi类中的函数返回给定的值,然后子类中的字符串类返回最后一个值.
我该怎么做?
我正在stackoverflow上阅读这个线程,但根据用户的说法,解决方案似乎是错误的,最重要的是,它无法解决我的问题,我不知道是因为答案是在python 2中还是现在。
但是,可以说我有这个代码
class A:
def say_hello(self):
print("Hi")
class B:
def say_hello(self):
print("Hello")
class C(A, B):
def say_hello(self):
super().say_hello()
print("Hey")
welcome = C()
welcome.say_hello()
Run Code Online (Sandbox Code Playgroud)
如何在不更改函数名称的情况下从 C 类调用 A 类和 B 类?正如我在另一个线程中读到的那样,您可以执行类似的操作,super(B, self).say_hello()但这似乎不起作用,但我不知道为什么。
假设我有一个列表,其中包括:
[['a','b','c','d']]
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法可以删除外部列表,以便输出
['a','b','c','d']
Run Code Online (Sandbox Code Playgroud)
我想到了类似 pop 的东西,但是删除了元素,我只想删除外部列表。
我知道我可以遍历双列表并将元素附加到新列表中,问题将得到解决,但我对该解决方案不满意,我想要一个更流畅的代码更清晰的解决方案。