类可以包含其自身的实例作为数据容器吗?
python 类可以包含其自身的实例吗?作为数据容器可能如下所示?
class A:
def __init__(self, val):
self.a = A(val)
self.val = val
aa = A(2)
#this will cause RuntimeError: maximum recursion depth exceeded
我的目的是使用此类作为数据容器,在它被初始化时包含一个副本,以减少深度复制操作。 它可以用作“撤消”链,以便在必要时有机会获取 init val 的值。
这样的行动可能吗?
Can a python class contain an instance of itself as a data container may look like this?
class A:
def __init__(self, val):
self.a = A(val)
self.val = val
aa = A(2)
#this will cause RuntimeError: maximum recursion depth exceeded
My purpose is using this class as a data container contain a copy inside if it when it be inited to reduce the deepcopy action.
It may used as an "undo" chain give a chance to get the init val's value when it's necessary.
Is it possible for such an action?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,一个类可以包含它自己的一个实例,只是由于其他人描述的原因,您无法在启动时创建它。
例如,这个类会执行此操作,
然后您可以实例化它并设置其自身的内部副本,如下所示:
并验证它是否可以使用:
Yes, a class can contain an instance of itself, you just can't create it on initiation for the reasons described by others.
For example this class will do it,
You can then instantiate it and set its inner copy of itself like this:
And verify it worked with:
这是行不通的,原因已经给出:
A(2)
并调用A.__init__
。A.__init__
调用A(val)
。A(val)
调用A.__init__
。我假设您这样做是为了记录
val
的情况;也就是说,如果稍后您决定将val
改为3
,则不会丢弃原始值2
。怎么样:代码
解释
A(object)
:类现在应该继承自object
。只是因为,基本上。@property
:这告诉Python每次我们请求A.val时,它都应该调用A.val()并返回结果。这是一个装饰器;查看property
内置函数以获取更多信息。@val.setter
:这与上面类似,但告诉 Python 每次我们尝试分配给A.val
时,它应该调用以下函数。它将值附加到历史列表中,而不是设置A.val
。This won't work, for the reason already given:
A(2)
and callsA.__init__
.A.__init__
callsA(val)
.A(val)
callsA.__init__
.I assume you're doing this so that you have a log of what
val
has been; that is, if sometime later you decide that you wantval
to be3
instead, you don't throw away the original value2
. How about:Code
Explanation
A( object )
: classes should now inherit fromobject
. Just because, basically.@property
: this tells python that every time we ask for A.val, it should call A.val() and return the result. This is a decorator; look up theproperty
builtin function for more information.@val.setter
: this is similar to the above, but tells Python that every time we try to assign toA.val
it should call the following function instead. Instead of settingA.val
, it appends the value to the history list.好吧,你在 self.a 中的类也有 self.a,所以没有尽头。我不确定我明白你正在做的事情的目的,但你可以尝试这样的事情:
Well, the class you have in self.a also has self.a, and so furher without an end. I'm not sure I get the purpose of what you are doing, but you might try something like this: