创建类属性而不通过 __setattr__

发布于 2024-09-05 17:10:17 字数 1766 浏览 3 评论 0原文

下面是我创建的一个类,用于轻松地将一堆数据存储为属性。 它们最终被存储在字典中。 我重写 __getattr____setattr__ 以不同类型的单位存储和检索值。 当我开始覆盖 __setattr__ 时,我在 __init__ 的第二行创建初始字典时遇到了麻烦,就像这样......

super(MyDataFile, self).__setattr__( '_data', {})

我的问题... 是否有更简单的方法通过 __setattr__ 来创建类级别属性? 另外,我应该担心保留一个单独的字典还是应该将所有内容存储在 self.__dict__ 中?

#!/usr/bin/env python

from unitconverter import convert
import re

special_attribute_re = re.compile(r'(.+)__(.+)')

class MyDataFile(object):

    def __init__(self, *args, **kwargs):
        super(MyDataFile, self).__init__(*args, **kwargs)
        super(MyDataFile, self).__setattr__('_data', {})

    #
    # For attribute type access
    #
    def __setattr__(self, name, value):
        self._data[name] = value

    def __getattr__(self, name):

        if name in self._data:
            return self._data[name]

        match = special_attribute_re.match(name)
        if match:
            varname, units = match.groups()
            if varname in self._data:
                return self.getvaras(varname, units)

        raise AttributeError

    #
    # other methods
    #
    def getvaras(self, name, units):
        from_val, from_units = self._data[name]
        if from_units == units:
            return from_val
        return convert(from_val, from_units, units), units

    def __str__(self):
        return str(self._data)



d = MyDataFile()

print d

# set like a dictionary or an attribute
d.XYZ = 12.34, 'in'
d.ABC = 76.54, 'ft'

# get it back like a dictionary or an attribute
print d.XYZ
print d.ABC

# get conversions using getvaras or using a specially formed attribute
print d.getvaras('ABC', 'cm')
print d.XYZ__mm

What I have below is a class I made to easily store a bunch of data as attributes.
They wind up getting stored in a dictionary.
I override __getattr__ and __setattr__ to store and retrieve the values back in different types of units.
When I started overriding __setattr__ I was having trouble creating that initial dicionary in the 2nd line of __init__ like so...

super(MyDataFile, self).__setattr__('_data', {})

My question...
Is there an easier way to create a class level attribute with going through __setattr__?
Also, should I be concerned about keeping a separate dictionary or should I just store everything in self.__dict__?

#!/usr/bin/env python

from unitconverter import convert
import re

special_attribute_re = re.compile(r'(.+)__(.+)')

class MyDataFile(object):

    def __init__(self, *args, **kwargs):
        super(MyDataFile, self).__init__(*args, **kwargs)
        super(MyDataFile, self).__setattr__('_data', {})

    #
    # For attribute type access
    #
    def __setattr__(self, name, value):
        self._data[name] = value

    def __getattr__(self, name):

        if name in self._data:
            return self._data[name]

        match = special_attribute_re.match(name)
        if match:
            varname, units = match.groups()
            if varname in self._data:
                return self.getvaras(varname, units)

        raise AttributeError

    #
    # other methods
    #
    def getvaras(self, name, units):
        from_val, from_units = self._data[name]
        if from_units == units:
            return from_val
        return convert(from_val, from_units, units), units

    def __str__(self):
        return str(self._data)



d = MyDataFile()

print d

# set like a dictionary or an attribute
d.XYZ = 12.34, 'in'
d.ABC = 76.54, 'ft'

# get it back like a dictionary or an attribute
print d.XYZ
print d.ABC

# get conversions using getvaras or using a specially formed attribute
print d.getvaras('ABC', 'cm')
print d.XYZ__mm

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挥剑断情 2024-09-12 17:10:17

示例中的 __setattr__ 除了将内容放入 _data 而不是 __dict__ 中删除之外,不执行任何操作。

__getattr__ 更改为使用 __dict__

将您的值和单位存储为简单的二元组。

Your __setattr__ in the example doesn't do anything except put things in _data instead of __dict__ Remove it.

Change your __getattr__ to use __dict__.

Store your value and units as a simple 2-tuple.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文