Skip to main content
 首页 » 编程设计

python之了解 python 描述符示例 (TypedProperty)

2024年10月24日12Renyi-Fan

这是在 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 

这是一个任意的设计决定吗?

请您参考如下方法:

所有 类的实例将共享相同的描述符实例(例如 TypedProperty)。因此,如果您将值存储在 TypedProperty 上,则 Foo 的所有实例都将具有相同的 name 和 num 值 值。这对于描述符来说通常是不可取的(或预期的)。

例如如果您运行以下脚本:

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 
 
 
class Foo(object): 
    name = TypedProperty2("name", str) 
 
f1 = Foo() 
f1.name = 'blah' 
 
f2 = Foo() 
print(f2.name) 
f2.name = 'bar' 
 
print(f1.name) 

您将看到以下输出:

blah 
bar 

所以我们可以看到最初 f2 有 f1 的名字,然后,在改变 f2 的名字之后,f1 选择了 f2 的名字。