【发布时间】:2018-02-03 08:56:30
【问题描述】:
有没有办法阻止一些但不是所有的参数被发送到超类?
我有一个验证用户输入的基类:
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继承自Base,并使用该方法检查其关键字
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中的超类。这是您的期望@CiaranWelsh 吗? -
我希望将
B().default_properties()中的a和b传递给A而不是B().default_properties()中的d。 -
我试过
del kwargs['d'],它确实有效。但是它不是很优雅,我想以此为基础构建一个 python 包——如果它有缺陷,我认为我最好找到一个没有缺陷的解决方案。感谢您的建议@Rawing
标签: python class inheritance subclass superclass