Object-oriented Reflection

Source: Internet
Author: User

Label (Space delimited): Reflection

This chapter focuses on the study of object-oriented reflection

When it comes to reflection, not the definition of reflection, let's consider a problem first:
If I have defined a class before, there is a class instantiation object, we can access the object's properties through the class;

Here we first define a class:

class People:    def __init__(self,name,age):        self.name=name        self.age=age    def talk(self):        print('%s is talking' %self.name)obj=People('engon',18)print(obj.talk)#这里是属性print(obj.name) #obj.__dict__{'name'}

The above example illustrates: We have previously accessed properties, methods, and objects.

  • If our program has interaction with the user, it requires the user to enter the attributes they want to access:
    Look at the code below, right?
class People:    def __init__(self,name,age):        self.name=name        self.age=age    def talk(self):        print('%s is talking' %self.name)obj=People('engon',18)choice=input('>>:')print(obj.choice)

The result of the above code execution is definitely not possible, because obj. must be the name of a property, not a string;

  • The key now is that we're going to be able to map the attributes through the user's string:
    Question: How to map an object property by string: (Here we need to learn several built-in methods)
    1.hasattr ()
class People:    def __init__(self,name,age):        self.name=name        self.age=age    def talk(self):        print('%s is talking' %self.name)obj=People('engon',18)print(hasattr(obj,'name'))#obj.name #obj.__dict__{'name'}print(hasattr(obj,talk))print(getattr(obj,'nameXXX',None))#获取print(getattr(obj,'talk',None))setattr(boj,'sex','male') #obj.sex='male'#设置模块print(obj.sex)delattr(obj,'age')#删除print(obj.__dict__)
Application of Reflection:

Through the code below we can call the property by receiving the user's input;

So that it can be mapped out;

Object-oriented Reflection

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.