如何使用 Python 创建带有属性的元组?
我有一个类 WeightedArc 定义如下:
class Arc(tuple):
@property
def tail(self):
return self[0]
@property
def head(self):
return self[1]
@property
def inverted(self):
return Arc((self.head, self.tail))
def __eq__(self, other):
return self.head == other.head and self.tail == other.tail
class WeightedArc(Arc):
def __new__(cls, arc, weight):
self.weight = weight
return super(Arc, cls).__new__(arc)
这段代码显然不起作用,因为 self
没有为 WeightArc.__new__
定义。如何将属性权重分配给 WeightArc 类?
I have a class WeightedArc defined as follows:
class Arc(tuple):
@property
def tail(self):
return self[0]
@property
def head(self):
return self[1]
@property
def inverted(self):
return Arc((self.head, self.tail))
def __eq__(self, other):
return self.head == other.head and self.tail == other.tail
class WeightedArc(Arc):
def __new__(cls, arc, weight):
self.weight = weight
return super(Arc, cls).__new__(arc)
This code clearly doesn't work, because self
isn't defined for WeightArc.__new__
. How do I assign the attribute weight to the WeightArc class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
原始代码的修复版本是:
另一种查看collections.namedtuple的verbose选项的方法,以查看如何子类tuple<的示例/em>:
您可以剪切、粘贴和修改此代码,或者只是从其子类化,如 中所示命名元组文档。
要扩展此类,请构建 Arc 中的字段:
The fixed-up version of your original code is:
Another approach to look at the verbose option for collections.namedtuple to see an example of how to subclass tuple:
You can cut, paste, and modify this code, or just subclass from it as shown in the namedtuple docs.
To extend this class, build off of the fields in Arc:
更好的是,为什么我们自己不使用namedtuple呢? :)
Better yet, why not use namedtuple ourselves? :)