有没有办法阻止一些但不是所有的参数被发送到超类?是否可以选择哪些kwargs传递给Python中的超类?
我有一个验证用户输入的基类:从Base
class Base(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
super(Base, self).__init__()
@staticmethod
def check_integrity(allowed, given):
"""
Verify user input.
:param allowed: list. Keys allowed in class
:param given: list. Keys given by user
:return:
"""
for key in given:
if key not in allowed:
raise Exception('{} not in {}'.format(key, allowed))
>>> base = Base()
>>> print base.__dict__
output[0]: {'kwargs': {}}
A
继承和使用方法,以检查它的关键字
class A(Base):
def __init__(self, **kwargs):
super(A, self).__init__(**kwargs)
self.default_properties = {'a': 1,
'b': 2}
self.check_integrity(self.default_properties.keys(), kwargs.keys())
>>> a = A(a=4)
>>> print a.__dict__
output[1]: {'default_properties': {'a': 1, 'b': 2}, 'kwargs': {'a': 4}}
我还要提到的是我已经拉出我在这个类中用于更新类属性的另一种方法,因为它是一个与问题无关的并发症(因此在上例中为什么a
未更新为4
)
在问题出现时,试图从A
继承和增加额外kwargs
子类:
class B(A):
def __init__(self, **kwargs):
super(B, self).__init__(**kwargs)
self.default_properties = {'a': 2,
'c': 3,
'd': 4}
self.check_integrity(self.default_properties.keys(), kwargs.keys())
>>> b = B(d=5)
Traceback (most recent call last):
File "/home/b3053674/Documents/PyCoTools/PyCoTools/Tests/scrap_paper.py", line 112, in <module>
b = B(d=5)
File "/home/b3053674/Documents/PyCoTools/PyCoTools/Tests/scrap_paper.py", line 96, in __init__
super(B, self).__init__(**kwargs)
File "/home/b3053674/Documents/PyCoTools/PyCoTools/Tests/scrap_paper.py", line 92, in __init__
self.check_integrity(self.default_properties.keys(), kwargs.keys())
File "/home/b3053674/Documents/PyCoTools/PyCoTools/Tests/scrap_paper.py", line 84, in check_integrity
raise Exception('{} not in {}'.format(key, allowed))
Exception: d not in ['a', 'b']
这里d
被传递到超类,即使它只是在子类必须的。但是,a
和b
自变量用于A
,应该从B
转换为A
。
'del kwargs ['d']'? –
需要通过'kwargs'来超类那些不在'self.default_properties'.Is this your expectation @CiaranWelsh? – Rajez
我想从'B()。default_properties()'''''''''a'和'b'从B()。default_properties()'传递给'A',而不是'd'。 – CiaranWelsh