简体   繁体   English

子类化namedtuple,__ new__和__init__

[英]Subclassing namedtuple, __new__ and __init__

I am very new to Python and am currently using Python 3.4 我是Python的新手,目前正在使用Python 3.4

Right now, I am apparently banging my head to figure out how best to create a customized immutable object by subclassing 'namedtuple'. 现在,我显然正在全力以赴,想出如何通过子类化'namedtuple'来最好地创建定制的不可变对象。

Here are my code that works without errors but I am getting way too many warning messages from my good friend PyCharm, so it was set upon me to find out if I am doing this correctly. 这是我的代码,可以正常运行,但是我的好朋友PyCharm收到了太多警告消息,因此我被迫确定是否正确执行此操作。

from collections import namedtuple

class Aloe(namedtuple('Plant', [
    'name',
    'color',
    'loveliness'
])):

    def __new__(cls, params):
        return super(Aloe, cls).__new__(
            cls,
            params.get('name'),
            params.get('color'),
            params.get('loveliness')
        )

    def __init__(self, params):
        print(self.name)
        super(Aloe, self).__init__()

When I call it, I get this. 当我打电话给我时,我明白了。

>>> aloe = Aloe(params)
>>> print(aloe)
Aloe(name='aloey', color='green', loveliness='extreme')


The first of warning come from __new__ block. 警告的第一个来自__new__块。

All my params.get('FIELD_NAME') are blamed for ' Unexpected argument '. 我的所有params.get('FIELD_NAME')被指责为“ 意外参数 ”。

Funny thing is, if my remove the arguments, I got, 有趣的是,如果我删除参数,我会得到,

TypeError: __new__() missing 1 required positional argument:

What does this thing really want me to do?! 这东西真的要我做什么?!


The second of warning come from __init__ block. 第二个警告来自__init__块。

super(Aloe, self).__init__() is blamed for ' Parameter 'typename' unfilled ' super(Aloe, self).__init__()被指责为' 参数'typename'未填充 '

So I gave it a good 'Plant' as the desired 'typename'. 因此,我给它一个好的'Plant'作为所需的“类型名称”。 Then I got, 然后我得到了

TypeError: object.__init__() takes no parameters

(ノಠ益ಠ)ノ彡┻━┻ (ノಠ益ಠ)ノ彡┻━┻


Back to the point, 回到重点,

  1. My code is working, but I get loads of warnings from PyCharm. 我的代码正在运行,但是我收到了来自PyCharm的大量警告。

  2. There seems absolutely no way I can satisfy PyCharm. 似乎绝对无法满足PyCharm。

So, I am concerned that I might be neglecting the Pythonic way of handling things. 因此,我担心自己可能会忽略Python处理事物的方式。 If I am, I wish I could use some tips. 如果我愿意,我希望可以使用一些技巧。

PyCharm is being overly protective here, and incorrect to boot. PyCharm在此过于保护,无法正确启动。 However, if all you wanted to do is provide some default values, I'd use a factory method: 但是,如果您只想提供一些默认值,则可以使用工厂方法:

class Aloe(namedtuple('Plant', 'name color loveliness')):
    @classmethod
    def from_row(cls, name=None, color=None, loveliness=None, **ignored):
        return cls(name, color, loveliness)

and use **params when creating one: 并在创建一个时使用**params

Aloe.from_row(**params)

This applies the key-value pairs from params as separate keyword arguments. 这会将来自params的键/值对用作单独的关键字参数。 Missing keys will set to None , extra keys are captured in **ignored and ignored. 缺少的键将设置为None ,多余的键将以**ignored和忽略的方式捕获。

If your database rows will always produce exactly the right 3 keys in a row dictionary, don't even bother with a factory method, just directly use a namedtuple and the above **params syntax: 如果您的数据库行将始终在行字典中生成恰好正确的3个键,那么甚至不用理会工厂方法,只需直接使用namedtuple和上面的**params语法即可:

Aloe(**params)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM