hasattr,getattr,setattr和delattr

'''
reflection
'''
def add(self):
    print("I am a newly bound method!")

class People(object):
    skin = "yellow"
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say(self, content):
        print("Said [%s]" % content)


choice = input(">>").strip()

# if choice in People.__dict__:
# print("There is this method")
# print(People.__dict__) #Print all class attributes and methods

# p = People("小白", "26")
# print(p.__dict__) #Print all instance attributes
p = People("小白", "26")

if hasattr(p, choice):
    #If it is a method, execute it directly
    try:
        func = getattr(p, choice)
        func("It is impossible to work part-time!")  
    #If the input is an attribute, a TypeError will be reported, and the attribute value will be printed directly
    except TypeError as e:
        print(func)
else:
    setattr(p, choice, add)
    func = getattr(p, choice)
    func(p)
#delattr(p, choice) #Delete attributes and methods

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324978549&siteId=291194637