030 reflection,

Source: Internet
Author: User

030 reflection,

### Reflection
# Getattr, hasattr, setattr, and delattr are related to fields in the class. For details, refer to the example.

#1 class Person: def _ init _ (self, name, age): self. name = name self. age = age def show_lover (self): print ('lover ') o = Person ('x', 21) B = 'name' print (o. _ dict _ [B]) #2 B = input ('>') if hasattr (o, B): v = getattr (o, B) # Get the delattr (o, B) setattr (o, 'age', 21) print (v) func = getattr (o, 'show _ lover ') # obtain method func ()
View Code

#3 obtain the fields of the Class Object

class  Person:    stat = '123'    def  __init__(self,name,age):        self.name = name        self.age = ager = getattr(Person,'stat')print(r)

#4 obtain functions and fields of other modules

# s.pyNAME = '_nbloser'def  func():    return'func'class  Person:    def  __init__(self):self.name = '_nbloser'
# Execution. pyimport sr1 = getattr (s, 'name') r2 = getattr (s, 'func') Pers = getattr (s, 'person') p1 = Pers () print (r1, r2 (), p1.name) # _ nbloser func _ nbloser

 

# Application example

Def f1 (): return 'homepage 'def f2 (): return 'News' def f3 (): return' extract 'import sinp = input ('> ') if hasattr (s, indium): func = getattr (s, indium) print (func () else: print (404)

 

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.