Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
理解python描述符示例(TypedProperty)_Python_Class_Descriptor - Fatal编程技术网

理解python描述符示例(TypedProperty)

理解python描述符示例(TypedProperty),python,class,descriptor,Python,Class,Descriptor,下面是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):

下面是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
值都将具有相同的值。对于描述符来说,这通常是不可取的(或预期的)

e、 g.如果运行以下脚本:

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
的名称