python-3.x - How to call super().__init__(*args, **kwargs) with super() a specific instance
问题描述
Given this setup:
class Foo:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def bar(self):
return Bar(self.arg1, self.arg2)
class Bar(Foo):
def __init__(self, arg1, arg2):
super().__init__(arg1, arg2)
if __name__ == '__main__':
foo = Foo(1, 2)
print(foo.bar().arg1)
print(foo.bar().arg2)
with Bar
being a subclass of Foo
is there a way to make Bar
in bar()
method in Foo
recognize arg1 and arg2 of its superclass without passing them as parameters and without getting arg1
and arg2
out of __init__()
?
解决方案
解释
为了使Bar
inFoo
的bar
方法能够识别其父类的arg1
和arg2
方法而不将它们作为参数传递,您可以将Foo
对象的属性复制到Bar
对象的属性。
这可以手动或自动完成,尽管自动化伴随着必须导入内置模块的成本inspect
。
解决方案
您可以手动执行此操作的方法是将Bar
' 对象的属性设置为等于Foo
对象的属性。由于Bar
该类继承自Foo
该类,因此您还需要覆盖以下__init__
方法Bar
:
class Foo:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def bar(self):
temp_bar = Bar()
temp_bar.arg1 = self.arg1
temp_bar.arg2 = self.arg2
return bar
class Bar(Foo):
# Overrides the __init__ method
def __init__():
pass
if __name__ == '__main__':
foo = Foo(1, 2)
print(foo.bar().arg1)
print(foo.bar().arg2)
第二种自动方式是将Foo
对象的自定义创建的属性复制到Bar
对象的属性中。这里inspect
需要内置模块来获取Foo
对象的属性,而我们可以只更新's 对象的__dict__
属性Bar
来复制属性:
import inspect
class Foo:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def bar(self):
temp_bar = Bar()
# Creates a dummy object
dummy = dir(type('Dummy', (object,), {}))
# Iterates through all Foo object's attributes
for item in inspect.getmembers(self):
# Since the dummy object only has built-in attributes,
# only custom-created ones will be used (in this case arg1 and arg2)
if item[0] not in dummy:
# Copies each attribute to temp_bar
setattr(temp_bar, *item)
return temp_bar
class Bar(Foo):
# Overrides the __init__ method
def __init__(self):
pass
if __name__ == '__main__':
foo = Foo(1, 2)
print(foo.bar().arg1)
print(foo.bar().arg2)
推荐阅读
- python - TypeError:“NoneType”对象不可下标 Odoo 11 自定义报告
- django - 如何优化查询 django rest-framework
- python - 从 pandas 数据框中为列中的不同值创建列表
- python - 我不能在 pygame 中使用一种以上的字体
- google-sheets - 保护细胞免受公众阅读
- javascript - 是否可以仅使用 html、css 和 javascript 动态创建 div?
- python - 如何根据环境变量使python函数使用字典中的值?
- spring-boot - 在 Spring Boot 2 上实现基于过滤器的 JWT 身份验证与 OAuth2 JWT 身份验证
- c++ - GetModuleHandle(nullptr) 上的 GetProcAddress() 在 MinGW 下失败
- android - ArrayList 显示它的大小为 0 即使在向其添加元素后也是如此