gpt4 book ai didi

python - 创建一流的对象,它的所有实例属性都是只读的,就像切片一样?

转载 作者:行者123 更新时间:2023-11-30 22:16:32 25 4
gpt4 key购买 nike

我的问题是如何创建像 slice 这样的类?

slice(内置类型)没有 __dict__ 属性甚至这个slicemetaclasstype

并且它没有使用__slots__,并且它的所有属性都是只读的并且它没有覆盖__setattr__ (这个我不确定,但看看我的代码,看看我是否正确)。

检查此代码:

# how slice is removing the __dict__ from the class object
# and the metaclass is type!!

class sliceS(object):
pass

class sliceS0(object):

def __setattr__(self, name, value):
pass

# this means that both have the same
# metaclass type.
print type(slice) == type(sliceS) # prints True

# from what i understand the metaclass is the one
# that is responsible for making the class object
sliceS2 = type('sliceS2', (object,), {})
# witch is the same
# sliceS2 = type.__new__(type, 'sliceS2', (object,), {})
print type(sliceS2) # prints type

# but when i check the list of attribute using dir
print '__dict__' in dir(slice) # prints False
print '__dict__' in dir(sliceS) # prints True

# now when i try to set an attribute on slice
obj_slice = slice(10)
# there is no __dict__ here
print '__dict__' in dir(obj_slice) # prints False
obj_sliceS = sliceS()
try:
obj_slice.x = 1
except AttributeError as e:
# you get AttributeError
# mean you cannot add new properties
print "'slice' object has no attribute 'x'"

obj_sliceS.x = 1 # Ok: x is added to __dict__ of obj_sliceS
print 'x' in obj_sliceS.__dict__ # prints True

# and slice is not using __slots__ because as you see it's not here
print '__slots__' in dir(slice) # print False

# and this why i'm saying it's not overriding the __settattr__
print id(obj_slice.__setattr__) == id(obj_sliceS.__setattr__) # True: it's the same object
obj_sliceS0 = sliceS0()
print id(obj_slice.__setattr__) == id(obj_sliceS0.__setattr__) # False: it's the same object

# so slice have only start, stop, step and are all readonly attribute and it's not overriding the __setattr__
# what technique it's using?!!!!

如何使这种一流对象的所有属性都是只读的,并且不能添加新属性。

最佳答案

问题是 Python 的内置 slice 类是用 C 语言编写的。当您使用 C-Python API 进行编码时,您可以编写可通过 __slots__< 访问的属性的等效内容 不使用任何从 Python 端可见的机制。 (您甚至可以拥有“真正的”私有(private)属性,这对于纯 Python 代码来说几乎是不可能的)。

Python 代码能够防止类实例出现 __dict__ 以及随后的“可以设置任何属性”的机制正是 __slots__ 属性。然而,与实际使用类时必须存在的 magic dunder 方法不同,__slots__ 上的信息是在创建类时使用的,而且只有在创建类时才会使用。因此,如果您担心的是最终类中有一个可见的 __slots__ ,您可以在公开它之前将其从类中删除:

In [8]: class A:
...: __slots__ = "b"
...:

In [9]: del A.__slots__

In [10]: a = A()

In [11]: a.b = 5

In [12]: a.c = 5
------------------------
AttributeError
...

In [13]: A.__slots__
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-13-68a69c802e74> in <module>()
----> 1 A.__slots__

AttributeError: type object 'A' has no attribute '__slots__'

如果您不希望在声明类的任何地方都显示 del MyClass.__slots__ 行,那么它是一个单行类装饰器:

def slotless(cls):
del cls.__slots__
return cls

@slotless
class MyClass:
__slots__ = "x y".split()

或者,您可以使用元类来自动创建和自动销毁Python可见的__slots__,以便您可以在类主体中声明描述符和属性,并保护该类针对额外属性:

class AttrOnly(type):
def __new__(metacls, name, bases, namespace, **kw):
namespace["__slots__"] = list(namespace.keys()) # not sure if "list(" is needed
cls = super().__new__(metacls, name, bases, namespace, **kw)
del cls.__slots__
return cls

class MyClass(metaclass=AttrOnly):
x = int
y = int

如果您想要纯 Python 只读属性,该属性在实例本身中没有可见的对应项(例如由 property 描述符使用的 ._x 来保持x 属性的值),最简单的方法是自定义 __setattr__ 。另一种方法是让元类在类创建阶段为每个属性自动添加只读属性。下面的元类执行此操作并使用 __slots__ 类属性来创建所需的描述符:

class ReadOnlyAttrs(type):
def __new__(metacls, name, bases, namespace, **kw):
def get_setter(attr):
def setter(self, value):
if getattr(self, "_initialized", False):
raise ValueError("Can't set " + attr)
setattr(self, "_" + attr, value)
return setter

slots = namespace.get("__slots__", [])
slots.append("initialized")
def __new__(cls, *args, **kw):
self = object.__new__(cls) # for production code that could have an arbitrary hierarchy, this needs to be done more carefully
for attr, value in kw.items():
setattr(self, attr, value)
self.initialized = True
return self

namespace["__new__"] = __new__
real_slots = []
for attr in slots:
real_slots.append("_" + attr)
namespace[attr] = property(
(lambda attr: lambda self: getattr(self, "_" + attr))(attr), # Getter. Extra lambda needed to create an extra closure containing each attr
get_setter(attr)
)
namespace["__slots__"] = real_slots
cls = super().__new__(metacls, name, bases, namespace, **kw)
del cls.__slots__
return cls

请记住,如果您愿意,您还可以自定义类的 __dir__ 方法,以便看不到 _x 阴影属性。

关于python - 创建一流的对象,它的所有实例属性都是只读的,就像切片一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49936714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com