zoukankan      html  css  js  c++  java
  • 描述符的应用

     1 class Typed:
     2     def __init__(self,key,expected_type):
     3         self.key=key
     4         self.expected_type=expected_type
     5     def __get__(self, instance, owner):
     6         print('get方法')
     7         return instance.__dict__[self.key]
     8     def __set__(self, instance, value):
     9         print('set方法')
    10         if not isinstance(value,self.expected_type):
    11             raise TypeError('%s 传入的类型不是%s' %(self.key,self.expected_type))
    12         instance.__dict__[self.key]=value
    13     def __delete__(self, instance):
    14         print('delete方法')
    15         instance.__dict__.pop(self.key)
    16 
    17 class People:
    18     name=Typed('name',str) #t1.__set__()  self.__set__()
    19     age=Typed('age',int) #t1.__set__()  self.__set__()
    20     def __init__(self,name,age,salary):
    21         self.name=name
    22         self.age=age
    23         self.salary=salary
    24 
    25 # p1=People('alex','13',13.3)
    26 p1=People(213,13,13.3)
  • 相关阅读:
    449. Serialize and Deserialize BST
    3. Longest Substring Without Repeating Characters
    2. Add Two Numbers
    240. Search a 2D Matrix II
    5. Longest Palindromic Substring
    数位DP专题(开坑。
    POJ 2356
    HDU 4055
    HDU 4054
    HDU 1559
  • 原文地址:https://www.cnblogs.com/yuanjie2019/p/10428418.html
Copyright © 2011-2022 走看看