Home >Backend Development >Python Tutorial >Python implements type checking of instance attributes
This article mainly introduces in detail how Python performs type checking on instance attributes. It has certain reference value. Interested friends can refer to it. I hope it can help you.
Case:
In a certain project, we implemented some classes and hoped to type-check their instance properties like static languages
p = Person()
p.name = 'xi_xi' # Must be str
p.age = 18 # Must be int
p.height = 1.75 # Must be float
Requirements:
You can specify the type for the instance variable name
Giving an incorrect type throws an exception
#!/usr/bin/python3 class Attr(object): """ 对Person类中属性进行类型检查 """ # 传入字段名字 + 指定字段类型 def __init__(self, name, style): self.name = name self.style = style # 取值 def __get__(self, instance, owner): return instance.__dict__[self.name] # 设值 def __set__(self, instance, value): # 判断参数类型是否满足条件 if isinstance(value, self.style): instance.__dict__[self.name] = value else: raise TypeError('need type: %s' % self.style) # 删除值 def __delete__(self, instance): del instance.__dict__[self.name] class Person(object): name = Attr('name', str) age = Attr('age', int) height = Attr('height', float) if __name__ == '__main__': p = Person() p.name = 'xi_xi' # p.name = 55 p.age = 18 p.height = 1.75 print(p.name, p.age, p.height) del p.height
Related recommendations:
JavaScript type checking and internal properties [[Class]]
The above is the detailed content of Python implements type checking of instance attributes. For more information, please follow other related articles on the PHP Chinese website!