gpt4 book ai didi

python - 如何将 "namedtuples"更改为 Python 中的类?

转载 作者:行者123 更新时间:2023-11-28 19:45:23 24 4
gpt4 key购买 nike

谁能举个例子?

在类中使用变量和在命名元组中使用变量有什么区别?

最佳答案

namedtuple 的返回值一个类。没有黑魔法。您不需要将 namedtuple 返回“转换”为类;它返回的正是那个。

namedtuple 创建一个继承自 __builtin__.tuple 的新类。当您调用 namedtuple('Point', 'x y')(1, 0) 时,您得到的是具有以下内容的元组对象 (1, 0)语法糖:

  • 一个 __dict__ 映射,其中 {'x': 1, 'y', 0}
  • 两个属性 xy 分别调用 __getitem__(0)__getitem__(1)
  • 返回 'Point(x=1, y=0)'
  • __repr__ 方法

除此之外,它只是一个元组对象。它的属性和属性数量是不可变的。

但是,我怀疑你的意思是你想使用 nametuple('Point', 'x, y') 而不是得到:

class Point:
def __init__(x, y):
self.x = x
self.y = y

在这种情况下,您滥用了 nametuple,而应该使用 type:

def init(self, x, y):
self.x, self.y = x, y
Point = type('Point', (object,), {'__init__': init})

关于python - 如何将 "namedtuples"更改为 Python 中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10453173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com