How does python check instance attributes and python instances?

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.