Код: Выделить всё
class A:
def __init__(self, arg):
print(f"A called with: {arg}")
class B:
def __init__(self, arg):
print(f"B called with {arg}")
class C(A, B):
pass
C(1)
Код: Выделить всё
A called with: 1
B called with: 1
Код: Выделить всё
A called with: 1
Код: Выделить всё
class C(A, B):
def __init__(self, arg):
super().__init__(arg)
super(A, self).__init__(arg)
Код: Выделить всё
class C(A, B):
def __init__(self, arg):
super(A, self).__init__(arg)
super(B, self).__init__(arg)
Какова причина: super(A, self) для вызова функции B class?
Обратите внимание, тоже пробовал это:
Код: Выделить всё
class C(A, B):
def __init__(self, arg):
super(C, self).__init__(arg)
Я также видел подобные методы (источник):
Код: Выделить всё
class First(object):
def __init__(self):
print "First(): entering"
super(First, self).__init__()
print "First(): exiting"
class Second(object):
def __init__(self):
print "Second(): entering"
super(Second, self).__init__()
print "Second(): exiting"
class Third(First, Second):
def __init__(self):
print "Third(): entering"
super(Third, self).__init__()
print "Third(): exiting"
Код: Выделить всё
class A:
def __init__(self, arg):
super(A, self).__init__(arg)
print(f"A called with: {arg}")
class B:
def __init__(self, arg):
super(B, self).__init__(arg)
print(f"B called with {arg}")
class C(A, B):
def __init__(self, arg):
super(C, self).__init__(arg)
Код: Выделить всё
Traceback (most recent call last):
File "censored\temp.py", line 15, in
C(1)
~^^^
File "censored\temp.py", line 13, in __init__
super(C, self).__init__(arg)
~~~~~~~~~~~~~~~~~~~~~~~^^^^^
File "censored\temp.py", line 3, in __init__
super(A, self).__init__(arg)
~~~~~~~~~~~~~~~~~~~~~~~^^^^^
File "censored\temp.py", line 8, in __init__
super(B, self).__init__(arg)
~~~~~~~~~~~~~~~~~~~~~~~^^^^^
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
Код: Выделить всё
class A:
def __init__(self, arg):
super(A, self).__init__(arg)
print(f"A called with: {arg}")
class B:
def __init__(self, arg):
print(f"B called with {arg}")
class C(A, B):
def __init__(self, arg):
super(C, self).__init__(arg)
Он работает отлично, но, на мой взгляд, это настолько неправильное решение, что я предпочитаю этого вообще не делать .
Я просто хочу знать, в чем причина: super(A, self) для вызова функции класса B?
Заранее спасибо!
Подробнее здесь: https://stackoverflow.com/questions/793 ... e-is-wierd
Мобильная версия