【发布时间】:2018-09-30 21:07:29
【问题描述】:
我的问题是如何创建像slice 这样的类?
slice(内置类型)没有__dict__ 属性
即使这个slice 的metaclass 是type。
并且它没有使用__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?!!!!
如何使这种一流的对象所有的属性都是只读的,你不能 添加新属性。
【问题讨论】:
-
...“一流的对象”是什么意思?
-
我猜你的意思是内置类型。
-
但是可以创建一个具有相同行为的类
-
如果您的意思是不覆盖
setattr或使用__slots__?写一个 C 扩展。或者使用property或其他一些描述符,而不实现__set__ -
@juanpa.arrivillaga 感谢您的评论我编辑了我的问题以消除冲突。问题是我如何创建一个行为类似于切片的类
标签: python python-2.7 metaclass readonly-attribute