1

我的问题是如何创建一个类slice

slice(内置类型) 没有__dict__属性,即使metaclassthisslicetype.

而且它没有使用__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?!!!!

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

4

1 回答 1

3

问题是 Python 的内置slice类是用 C 编写的。当您使用 C-Python API 进行编码时,您可以编写与可访问的属性等效的代码,__slots__而无需使用 Python 端可见的任何机制。(您甚至可以拥有“真正的”私有属性,这在纯 Python 代码中几乎是不可能的)。

用于 Python 代码的机制能够防止__dict__类的实例和随后的“可以设置任何属性”__slots__正是该属性。但是,与实际使用类时必须存在的魔术方法不同,在__slots__创建类时才使用 on 的信息,并且仅在那时才使用。所以,如果你关心的是__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 visible __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 只读属性(例如描述符._x用于property保留x属性值的 a ),直接的方法是自定义__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不会看到阴影属性。

于 2018-04-20T19:56:23.370 回答