程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python uses descriptors to implement attribute type checking

編輯:Python

1、 How to use descriptors to type check instance properties ?

         Actual case :

                 In a project , We implemented some classes , And hope to be like statically typed languages (C,C++,Java) Type check their instance properties .

 p = Person()
p.name = 'Bob' # The name attribute must be str
p.age = 18 # Age must be int
p.height = 1.83 # Height must be float

         requirement :(1) You can specify the type for the instance variable name

                  (2) Throw an exception when giving an incorrect type

         Solution :

                 Use descriptors to implement properties that require type checking : respectively __get__, __set__,__delete__ Method , stay __set__ Internal use isinstance Function to do type checking .

         expand :  Statically typed language variables can only refer to an object of a certain type and cannot be changed . Type checking is done by the compiler during the compilation phase , about Python In dynamic typing language, a variable can refer to any type of object and can change in real time , That is, the interpreter cannot complete type checking , You can only do it yourself .

         What is a descriptor ? Descriptors contain __get__, __set__,__delete__ The class of such a method , As long as one of these three methods is included, it is a descriptor .

         Instance attribute refers to taking an instance of another class as an attribute of a class .

2、 Code demonstration

(1) Descriptor Definition and access process introduction

class Descriptor(object):
def __get__(self, instance, cls):
# instance Used to distinguish between using classes to access x, Or use instances to access x
print('in __get__', instance, cls)
return instance.__dict__['x']
def __set__(self, instance, value):
# stay set Check the type in
print('in __set__')
instance.__dict__['x'] = value
def __delete__(self, instance):
print('in __del__')
class A(object):
# Define a class attribute in a class x
x = Descriptor()
a = A()
# Will be Descriptor Of __get__ Method intercepted
print(a.x)
# Use classes directly A Access class properties ,instance Will be introduced into None
print(A.x)
# Will be Descriptor Of __set__ Method intercepted
a.x = 5
# Will be Descriptor Of __del__ Method intercepted
del a.x
'''
Generally speaking, among these methods of descriptor, what is accessed is instance.__dict__ This dictionary ,
That is to operate on its real attributes .
'''
a = A()
a.x = 5
print(a.__dict__)

(2) The implementation uses the descriptor to check the instance property type

class Attr(object):
def __init__(self, name, type_):
self.name = name
self.type_ = type_
def __get__(self, instance, cls):
return instance.__dict__[self.name]
def __set__(self, instance, value):
# Check the field type
if not isinstance(value, self.type_):
raise TypeError('expected an %s' % self.type_)
instance.__dict__[self.name] = value
def __delete__(self, instance):
del instance.__dict__[self.name]
class Person(object):
# Define a name Field , Application descriptor instance
name = Attr('name', str)
age = Attr('age', int)
height = Attr('height', float)
p = Person()
p.name = 'Bob'
print(p.name)
# age The assignment string type throws an exception error
# p.age = '17'


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved