“追加”而不是覆盖超类实例变量
在 Python 中,有没有办法做这样的事情?
class A():
var = "1, 2, 3"
class B():
var = ... ", 4"
instance = B()
instance.var # = 1, 2, 3, 4
Is there a way, in Python, to do something like this?
class A():
var = "1, 2, 3"
class B():
var = ... ", 4"
instance = B()
instance.var # = 1, 2, 3, 4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题中给出的示例既不使用超类也不使用实例变量。从问题的标题来看,想必您想同时使用两者。下面是它如何工作的示例:
请注意,您的示例只是使用类似于命名空间的类将属性分配给不相关的类。这是完全合理的,但不完全符合你的要求:
The example given in the question uses neither a superclass nor an instance variable. From the title of the question, presumably you wanted to use both. Here's an example of how it would work:
Note that your example simply assigns attributes to unrelated classes, using the classes sort-of like namespaces. Which is perfectly reasonable, but not quite what you asked:
你不能追加,你可以替换,但你可以用包含原始内容的表达式替换:
这只是为了简单的用途,但更有趣的解决方案可能是使用描述符;最简单的方法是使用
property
,它适用于
B
的实例,但不适用于B
本身(如第一个示例)。要恢复它,您必须实现自己的描述符:它在类上和在类的实例上同样有效
you can't append, you replace, but you can replace by an expression that includes the original:
That does it for simple uses, but a more interesting solution might be to use a descriptor; The easy way is to use
property
Which works for instances of
B
, but not forB
itself (as in the first example). To get that back, you must implement your own descriptor:Which works equally well on the class as it does on instances of the class