[問題] class繼承 & __init__
不好意思,這個問題我不會直接描述,要請大家看一段sample code
--
from collections import UserList
# Python 3.5's source code:
# class UserList(MutableSequence):
# def __init__(self, initlist):
# ...
# (no super().__init__() here)
# 這是一個重要的parent class
class A(object):
def __init__(self, data, name, **kwargs):
super().__init__(data, **kwargs)
self.name = name
# class B的__init__執行的時候不會有問題,因為super().__init__會用
# UserList.__init__(...)
class B(A, UserList):
def __init__(self, data, name, path, **kwargs):
super().__init__(data, name, **kwargs)
self.path = path
# 這裡的__init__執行時候會出現error:
# object.__init__() takes no arguments
# 因為我在class A的__init__()中有呼叫super().__init__(data, **kwargs)
# 而其會對應到object.__init__() --> 不需要參數
class C(A):
def __init__(self, data, name, **kwargs):
super().__init__(data, name, **kwargs)
問題:
要如何解決class A __init__碰到的這種狀況?
我目前的想法是用try ... except 去嘗試兩種不同的super().__init__(...)
有比較推薦的解法嗎? 謝謝
※ 編輯: walelile (1.171.183.206), 10/25/2015 20:49:50
→
10/25 21:52, , 1F
10/25 21:52, 1F
→
10/26 00:45, , 2F
10/26 00:45, 2F
→
10/26 00:46, , 3F
10/26 00:46, 3F
→
10/26 01:08, , 4F
10/26 01:08, 4F
因為A會跟UserList, UserDict等collections作搭配,而其__init__唯一的參數名不同,
所以我沒辦法直接用**kwargs,因此我用"data"當作pos arg,並傳給collections。
把A __init__()中的data換成*args看起可以正常跑。
謝謝大家的指點
※ 編輯: walelile (1.171.183.206), 10/26/2015 05:22:07
Python 近期熱門文章
PTT數位生活區 即時熱門文章