1. 程式人生 > >描述符應用

描述符應用

文章目錄

# 描述符必須定義成資料描述符
class Typed:
    def __get__(self, instance, owner):
        print('>>get')
        print(instance)
        print(owner)

    def __set__(self, instance, value):
        print('>>set')
        print(instance)
        print(value)

    def __delete__(self, instance):
        print('>>delete')
        print(instance)

class People:
    name = Typed()
    def __init__(self, name, age, salary):
        self.name = name
        self.age = age
        self.salary = salary

p1 = People('egon', 22, 9998.05)
print('>>instance %s' % p1)
p1.name
p1.name = 220
print(p1.__dict__)

'''
>>set
<__main__.People object at 0x000001E06B2C6550>
egon
>>instance <__main__.People object at 0x000001E06B2C6550>
>>get
<__main__.People object at 0x000001E06B2C6550>
<class '__main__.People'>
>>set
<__main__.People object at 0x000001E06B2C6550>
220
{'age': 22, 'salary': 9998.05}
'''

限制資料型別

# 描述符必須定義成資料描述符
class Typed:
    def __init__(self, key, type):
        self.key = key
        self.type = type

    def __get__(self, instance, owner):
        print('>>get')
        # print('>>get instance:%s' % instance)
        # print('>>get owner:%s' % owner)
        return instance.__dict__[self.key]

    def __set__(self, instance, value):
        print('>>set')
        # print('>>set instance:%s' % instance)
        # print('>>set value:%s' % value)
        if not isinstance(value, self.type):
            raise TypeError('%s輸入的值不是%s' % (self.key, self.type))
        instance.__dict__[self.key] = value

    def __delete__(self, instance):
        print('>>delete')
        # print(instance)
        instance.__dict__.pop(self.key)

class People:
    name = Typed('name', str)
    age = Typed('age', int)
    def __init__(self, name, age, salary):
        self.name = name
        self.age = age
        self.salary = salary

p1 = People('lupe', 22, 9998.05)
# 報錯
# p2 = People(123, '22', 9998.05)