相关疑难解决方法(0)

在python中,如何将类对象转换为dict

假设我在python中有一个简单的类

class Wharrgarbl(object):
    def __init__(self, a, b, c, sum, version='old'):
        self.a = a
        self.b = b
        self.c = c
        self.sum = 6
        self.version = version

    def __int__(self):
        return self.sum + 9000

    def __what_goes_here__(self):
        return {'a': self.a, 'b': self.b, 'c': self.c}
Run Code Online (Sandbox Code Playgroud)

我可以很容易地将它转换为整数

>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> int(w)
9006
Run Code Online (Sandbox Code Playgroud)

哪个好极了!但是,现在我想以类似的方式把它变成一个字典

>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> dict(w)
{'a': 'one', 'c': 'three', 'b': 'two'}
Run Code Online (Sandbox Code Playgroud)

我需要为此定义什么?我试图取代这两个__dict__dict__what_goes_here__,但dict(w)导致了TypeError: Wharrgarbl object is …

python

65
推荐指数
5
解决办法
6万
查看次数

子类化Python namedtuple

Python的namedtuple作为一个轻量级,不可变的数据类非常有用.我喜欢将它们用于簿记参数而不是字典.当需要更多功能时,例如简单的文档字符串或默认值,您可以轻松地将namedtuple重构为类.但是,我已经看到继承自namedtuple的类.他们获得了什么功能,他们失去了什么表现?例如,我会将其实现为

from collections import namedtuple

class Pokemon(namedtuple('Pokemon', 'name type level')):
    """
    Attributes
    ----------
    name : str
        What do you call your Pokemon?
    type : str
        grass, rock, electric, etc.
    level : int
        Experience level [0, 100]
    """
     __slots__ = ()
Run Code Online (Sandbox Code Playgroud)

唯一的目的是能够干净地记录attrs,并__slots__用于防止创建__dict__(保持namedtuples的轻量级特性).

是否有更好的建议使用轻量级数据类来记录参数?注意我使用的是Python 2.7.

python namedtuple

12
推荐指数
1
解决办法
7325
查看次数

标签 统计

python ×2

namedtuple ×1