How does python check instance attributes and python instances?
The examples in this article share with you the python code for checking the type of instance attributes for your reference. The details are as follows:
Case:
In a project, we implement some classes and want to perform type checks on their instance attributes like static languages.
P = Person ()
P. name = 'Xi _ Xi' # It Must Be str
P. age = 18 # It Must Be int
P. height = 1.75 # It Must Be float
Requirements:
You can specify a type for the instance variable name.
An exception is thrown when an incorrect type is assigned.
#! /Usr/bin/python3 class Attr (object ): "type check for attributes in the Person class" # input field name + specified Field Type def _ init _ (self, name, style): self. name = name self. style = style # value: def _ get _ (self, instance, owner): return instance. _ dict _ [self. name] # set value def _ set _ (self, instance, value): # determine whether the parameter type meets the condition if isinstance (value, self. style): instance. _ dict _ [self. name] = value else: raise TypeError ('need type: % s' % self. style) # delete 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
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.