python『学习之路03』反射

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/11/22 20:35
# @Author : mixiu26

def bulk(self):
print("%s is yelling..." % self.name)

class Dog(object):
def __init__(self,name):
self.name = name

def eat(self,food):
print("%s is eating %s" % (self.name,food))

d = Dog("yaya")

# 场景: 根据用户输入判断用户的使用场景,如--- >> input eat ---- >>eat(); input sleep ---- >> sleep()
# 首先我们获取用户输入时得到的是字符串,那我们怎么判断用户输入的字符串和方法中的是一致的呢? 我不能逐一去判断
# 用户输入的字符串,因为可能我们内部有成百上千个方法,那怎么办?所以呢,我们就需要一个方法,可以动态的匹配类中的
# 方法和用户输入的字符串是否相同

# print(hasattr(d,choice)) # 动态的匹配类中是否有和用户输入一致的属性
# # 映射内存地址:
# # print(getattr(d,choice)) # <bound method Dog.eat of <__main__.Dog object at 0x0000000002909E80>>
# getattr(d,choice)() # ---- >> 映射内存地址,加上() 括号就可直接调用了

# so 动态匹配反射版:
choice = input(">>>: ").strip()
# if hasattr(d,choice): # 通过hasattr 去判断用户输入是否和对象中的属性有一致的,有就通过getattr来获取并调用它
# # # getattr(d,choice)("break")
# # # func = getattr(d,choice) # 先给对象赋值,在调用方法,因为有时会有传参
# # # func("brake")
# #
# # # 修改成员属性值:
# # setattr(d,choice,"ronghua") # ----- >> 将成员的值修改为ronghua
# # 删除成员属性值:
# delattr(d,choice) # --- : 删除name 属性值
#
# else:
# # 如果用户输入的数据在d中没有对应的对象映射,那么就走else --- > age --- >print 22 ---- > name = yaya
# # setattr(d,choice,bulk)
# # d.bulk(d)
# # 设置成员属性:
# setattr(d,choice,22) # ----- >> 给对象添加新属性
# print(getattr(d,choice)) # choice = name ---- >> print---- >> 22

# print(d.name) AttributeError: 'Dog' object has no attribute 'name'

if hasattr(d,choice):
getattr(d,choice) # ---- >> 判断str是否有对应属性在对象中,有就打印
else: # ---- >> 没有,就给对象添加该属性
# setattr(d,choice,None) # ---- >> 给对象设置属性值None
# v = getattr(d,choice) # ---- >> 打印对象新添加的属性值
# print(v) # ---- >> None

# 新增成员属性为内存地址:
setattr(d,choice,bulk)
func = getattr(d,choice) # ---- >> 如果添加的是内存地址,其实就相当于给他添加引用, d. choice = bulk --- >>不能写死
func(d)
原文地址:https://www.cnblogs.com/mixiu26/p/7881448.html