【发布时间】:2016-01-19 19:03:51
【问题描述】:
以下是 Python 书籍中一些代码的略微修改版本:
class TypedProperty(object):
def __init__(self,name,type,default=None):
self.name = "_" + name
self.type = type
self.default = default if default else type()
def __get__(self,instance,cls):
return getattr(instance,self.name,self.default)
def __set__(self,instance,value):
if not isinstance(value,self.type):
raise TypeError("Must be a %s" % self.type)
setattr(instance,self.name,value)
class Foo(object):
name = TypedProperty("name",str)
num = TypedProperty("num",int,42)
f = Foo()
f.name = 'blah'
我的问题:我们为什么要在 f 中创建属性?在上面的代码中,TypedProperty 被写成 f.name = 'blah' 在实例 f 中创建属性“_name”。
为什么不将值保存为 TypedProperty 类的属性?这是我的想法:
class TypedProperty2(object):
def __init__(self, val, typ):
if not isinstance(val, typ):
raise TypeError()
self.value = val
self.typ = typ
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, val):
if not isinstance(val, self.typ):
raise TypeError()
self.value = val
这是一个随意的设计决定吗?
【问题讨论】:
标签: python class descriptor