我想在内部使用namedtuples,但我希望保持与给我一个普通元组的用户的兼容性.
from collections import namedtuple
tuplePi=(1,3.14,"pi") #Normal tuple
Record=namedtuple("MyNamedTuple", ["ID", "Value", "Name"])
namedE=Record(2, 2.79, "e") #Named tuple
namedPi=Record(tuplePi) #Error
TypeError: __new__() missing 2 required positional arguments: 'Value' and 'Name'
tuplePi.__class__=Record
TypeError: __class__ assignment: only for heap types
Run Code Online (Sandbox Code Playgroud) 我试图pprint从pprint,但其产量只有一条线路,也没有多输出和无压痕.
我有一个命名元组,我赋值如下:
class test(object):
self.CFTs = collections.namedtuple('CFTs', 'c4annual c4perren c3perren ntfixing')
self.CFTs.c4annual = numpy.zeros(shape=(self.yshape, self.xshape))
self.CFTs.c4perren = numpy.zeros(shape=(self.yshape, self.xshape))
self.CFTs.c3perren = numpy.zeros(shape=(self.yshape, self.xshape))
self.CFTs.ntfixing = numpy.zeros(shape=(self.yshape, self.xshape))
Run Code Online (Sandbox Code Playgroud)
有没有办法循环命名元组的元素?我试过这样做,但不起作用:
for fld in self.CFTs._fields:
self.CFTs.fld= numpy.zeros(shape=(self.yshape, self.xshape))
Run Code Online (Sandbox Code Playgroud) 几周前我花了一些时间调查这个collections.namedtuple模块.该模块使用工厂函数将动态数据(新namedtuple类的名称和类属性名称)填充到一个非常大的字符串中.然后exec使用字符串(表示代码)作为参数执行,并返回新类.
有没有人知道为什么这样做,当有一种特定的工具可供现有的这种东西,即元类?我自己没有尝试过这样做,但似乎namedtuple模块中发生的一切都可以使用namedtuple元类轻松完成,如下所示:
class namedtuple(type):
Run Code Online (Sandbox Code Playgroud)
等等
我想知道enum和namedtuple之间有什么区别,以及何时应该使用一个而不是另一个.
这个问题与来自python中的基类的Inherit namedtuple相反,其目的是从namedtuple继承子类,反之亦然.
在正常继承中,这有效:
class Y(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
class Z(Y):
def __init__(self, a, b, c, d):
super(Z, self).__init__(a, b, c)
self.d = d
Run Code Online (Sandbox Code Playgroud)
[OUT]:
>>> Z(1,2,3,4)
<__main__.Z object at 0x10fcad950>
Run Code Online (Sandbox Code Playgroud)
但如果基类是namedtuple:
from collections import namedtuple
X = namedtuple('X', 'a b c')
class Z(X):
def __init__(self, a, b, c, d):
super(Z, self).__init__(a, b, c)
self.d = d
Run Code Online (Sandbox Code Playgroud)
[OUT]:
>>> Z(1,2,3,4)
Traceback (most recent call …Run Code Online (Sandbox Code Playgroud) 我有以下命名的元组:
from collections import namedtuple
ReadElement = namedtuple('ReadElement', 'address value')
Run Code Online (Sandbox Code Playgroud)
然后我想要以下内容:
LookupElement = namedtuple('LookupElement', 'address value lookups')
Run Code Online (Sandbox Code Playgroud)
两个命名元组之间存在重复,如何将ReadElement子类化为包含其他字段?
class LookupElement(ReadElement):
def __new__(self, address, value, lookups):
self = super(LookupElement, self).__new__(address, value)
l = list(self)
l.append(lookups)
return tuple(l)
Run Code Online (Sandbox Code Playgroud)
然而,在新语句中创建了元组,如果我将self修改为列表,我将丢失类型信息,我该如何避免这种情况?
PEP-557引入了数据类到Python标准库,基本上可以填补因为同样的作用collections.namedtuple和typing.NamedTuple.现在我想知道如何分离使用namedtuple仍然是更好的解决方案的用例.
当然,dataclass如果我们需要,所有的功劳都归功于:
property 装饰器,可管理的属性在同一个PEP中简要解释了数据类的优点:为什么不使用namedtuple.
但是对于namedtuples这个相反的问题怎么样:为什么不使用dataclass呢?我想从性能的角度来看,名字元组可能更好,但尚未确认.
让我们考虑以下情况:
我们将页面维度存储在一个小容器中,该容器具有静态定义的字段,类型提示和命名访问.不需要进一步散列,比较等.
NamedTuple方法:
from typing import NamedTuple
PageDimensions = NamedTuple("PageDimensions", [('width', int), ('height', int)])
Run Code Online (Sandbox Code Playgroud)
DataClass方法:
from dataclasses import dataclass
@dataclass
class PageDimensions:
width: int
height: int
Run Code Online (Sandbox Code Playgroud)
哪种解决方案更可取,为什么?
PS这个问题不是以任何方式重复那个问题,因为我在这里询问的是哪个命名元组更好,而不是区别(我在询问之前检查了文档和来源)
我想创建一个namedtuple代表短位域中的各个标志的代码.我正在尝试将其子类化,以便在创建元组之前解压缩位域.但是,我目前的尝试不起作用:
class Status(collections.namedtuple("Status", "started checking start_after_check checked error paused queued loaded")):
__slots__ = ()
def __new__(cls, status):
super(cls).__new__(cls, status & 1, status & 2, status & 4, status & 8, status & 16, status & 32, status & 64, status & 128)
Run Code Online (Sandbox Code Playgroud)
现在,我的经验super()是有限的,我的经验__new__实际上是不存在的,所以我不太清楚该怎么做(对我来说)神秘的错误TypeError: super.__new__(Status): Status is not a subtype of super.谷歌搜索和挖掘文档并没有产生什么启发.
救命?
正如PythonCookbook中提到的,*可以在元组之前添加,*这里的意思是什么?
第1.18章.将名称映射到序列元素:
from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price'])
s = Stock(*rec)
# here rec is an ordinary tuple, for example: rec = ('ACME', 100, 123.45)
Run Code Online (Sandbox Code Playgroud)
在同一部分,**dict提出:
from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price', 'date', 'time'])
# Create a prototype instance
stock_prototype = Stock('', 0, 0.0, None, None)
# Function to convert a dictionary to a Stock
def dict_to_stock(s):
return stock_prototype._replace(**s)
Run Code Online (Sandbox Code Playgroud)
什么是**这里的功能?
namedtuple ×10
python ×10
python-3.x ×3
super ×2
enums ×1
inheritance ×1
metaclass ×1
new-operator ×1
oop ×1
pep ×1
pprint ×1
python-2.7 ×1
python-3.7 ×1
tuples ×1