相关疑难解决方法(0)

在Python 3中动态更改__slots__

假设我有一个班级 __slots__

class A:
    __slots__ = ['x']

a = A()
a.x = 1   # works fine
a.y = 1   # AttributeError (as expected)
Run Code Online (Sandbox Code Playgroud)

现在我要改变__slots__A.

A.__slots__.append('y')
print(A.__slots__)   # ['x', 'y']
b = A()
b.x = 1   # OK
b.y = 1   # AttributeError (why?)
Run Code Online (Sandbox Code Playgroud)

b是在改变之后创建__slots__A,所以Python原则上可以为内存分配内存b.y.为什么没有?

如何正确修改__slots__类,以便新实例具有修改后的属性?

python slots python-3.x

5
推荐指数
2
解决办法
2256
查看次数

动态更改__slots__

我正在研究一个需要__dict__通过__init__注入赋予它属性的类,如下所示:

class Torrent(Model):
    def __init__(self, d):
        super(Torrent, self).__init__('torrents')
        self.__dict__ = d
Run Code Online (Sandbox Code Playgroud)

并且需要确保不要更改对象的结构,因为实例最终会在NOSQL数据库中结束.我认为这__slots__可能会有所帮助,但我需要动态定义它.

有没有一种方法可以在没有元类的情况下实现它?

python dictionary class

3
推荐指数
1
解决办法
1364
查看次数

标签 统计

python ×2

class ×1

dictionary ×1

python-3.x ×1

slots ×1