如何解决是否可以将类类型的对象作为另一个类中的参数传递,以便我不必再次初始化? Python 3.x
我使用了两个类 Foo
和 Bar
,后者继承了第一个类。
运行 Foo
可能需要一些时间,当我需要运行 Bar
时,我不想再次运行它。
class Foo:
def __init__(self):
self.something = "something"
self.another_variable = 10
# and many other variables
def do_something(self):
self.something = "something else"
self.another_variable = 100
# and more operations on the other variables
print(f"This takes some time. We have {self.something!r} Now.")
foo = Foo()
foo.do_something() # This takes some time. We have 'something else' Now.
class Bar(Foo):
def __init__(self,foo=None):
if isinstance(foo,Foo):
self.something = foo.something
self.another_variable = foo.another_variable
# ...
# this is the part that I want to generalize
# with something that would intuitively look like 'self = foo'
else:
Foo.__init__(self)
self.do_something()
def print_something(self):
print(self.something)
bar = Bar(foo=foo)
bar.print_something() # AttributeError: 'Bar' object has no attribute 'something'
我想做一些类似 self = foo
的事情,这样 foo
所做的一切都可以传递给 bar
。
我知道我可以先执行 Bar().foo()
再执行 Bar().bar()
,这就是我现在实际执行的操作,但我只想在稍后阶段初始化 bar
。
有可能吗?
解决方法
如果我没听错的话,你可以用一个标志(这里命名为 self.processed
)来做到这一点:
from time import sleep
class Foo:
def __init__(self):
self.something = "something"
self.processed = False
def do_something(self):
self.something = "something else"
sleep(1)
self.processed = True
print(f"This takes some time. We have {self.something!r} now.")
foo = Foo()
foo.do_something() # This takes some time. We have 'something else' now.
class Bar(Foo):
def __init__(self,foo=None):
if isinstance(foo,Foo):
super().__init__()
if not foo.processed:
self.do_something()
def print_something(self):
print(self.something)
bar = Bar(foo=foo)
bar.print_something()
输出:
This takes some time. We have 'something else' now.
something else
所以在 Bar
的初始化中,do_something
方法只有在我们之前没有调用过的情况下才会被调用(在 foo
上)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。