Python面试题之Python对象反射、类反射、模块反射
python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)
一、getattr
对象获取
class Manager:
role = "管理员"
def __init__(self,name,sex,phone,mail):
self.name = name
self.sex = sex
self.phone = phone
self.mail = mail def createClass(self):
print("create class") def createTeacher(self):
print("createTeacher") def createStu():
print("createStu") manager = Manager("safly","男",123456,123456) print("---对象获取对象方法-----")
f = getattr(manager,"createClass")
f() print("---对象获取对象属性-----")
name = getattr(manager,"name")
print(name) print("---对象获取类属性-----")
role = getattr(manager,"role")
print(role) print("---对象获取类属性(可以设置默认值)-----")
import logging
if hasattr(manager,"role1"):
role = getattr(manager,"role1","roleDefault")
print(role)
else:
logging.warn("没有role属性")
role = getattr(manager, "role1", "roleDefault")
print(role)
类获取
class Manager:
role = "管理员"
def createClass(self):
print("create class") def createStu():
print("createStu") m = Manager() f = getattr(Manager,"createClass")
f(Manager) f = getattr(Manager,"createClass")
f(m) role = getattr(Manager,"createStu")
role() #对象获取类属性
role = getattr(Manager,"role")
print(role)
输出如下:
create class
create class
createStu
管理员
二、setattr
设置类属性、方法
class Manager:
role = "管理员"
def __init__(self,name,sex,phone,mail):
self.name = name
self.sex = sex
self.phone = phone
self.mail = mail def createClass(self):
print("create class") def createTeacher(self):
print("createTeacher") def createStu():
print("createStu") manager = Manager("safly","男",123456,123456) print("----设置类属性------")
setattr(Manager,"country","china")
print(Manager.country) print("----删除类属性------")
delattr(Manager,"country")
# #删除报错
# print(Manager.country)
print("----设置类方法------")
def Method(parm):
print("我是被绑定的class之外的方法parm--",parm) setattr(Manager,"Method",Method)
Manager.Method("saf")
Manager.Method(Manager)
Manager.Method(manager) def Method():
print("我是被绑定的class之外的方法parm--")
setattr(Manager,"Method",Method)
Manager.Method()
输出如下:
E:\python\python_sdk\python.exe E:/python/py_pro/demo.py
----设置类属性------
china
----删除类属性------
----设置类方法------
我是被绑定的class之外的方法parm-- saf
我是被绑定的class之外的方法parm-- <class '__main__.Manager'>
我是被绑定的class之外的方法parm-- <__main__.Manager object at 0x0343B4B0>
我是被绑定的class之外的方法parm-- Process finished with exit code 0
设置对象属性、方法
class Manager:
role = "管理员"
def __init__(self,name,sex,phone,mail):
self.name = name
self.sex = sex
self.phone = phone
self.mail = mail def createClass(self):
print("create class") def createTeacher(self):
print("createTeacher") def createStu():
print("createStu") manager = Manager("safly","男",123456,123456) print("----设置对象属性------")
setattr(manager,"age",20)
print(manager.age) print("----删除对象属性------")
delattr(manager,"age")
# 'Manager' object has no attribute 'age'
# print(manager.age) print("---对象不能删除类属性---")
setattr(Manager,"country","china")
print(Manager.country)
# delattr(manager,"country")
# print(Manager.country) print("----设置对象方法------")
def create_course(self):
print('创建了一个课程') setattr(manager,'create_course',create_course)
manager.create_course(manager) def create_grade():
print('创建了一个班级')
setattr(manager,'create_grade',create_grade)
manager.create_grade()
输出如下:
E:\python\python_sdk\python.exe E:/python/py_pro/demo.py
----设置对象属性------
20
----删除对象属性------
---对象不能删除类属性---
china
----设置对象方法------
创建了一个课程
创建了一个班级 Process finished with exit code 0
三、模块反射
创建一个模块mokuai.py
a = 1
def method(rag):
print(rag)
return ""
然后在python.py中导入以上模块
import mokuai
print(getattr(mokuai,"a"))
method = getattr(mokuai,"method")
ret = method(8888)
print(ret)
输出如下:
1
8888
666
四、反射本模块函数、变量
aa = 11
def method():
print("---method---")
import sys print(sys.modules[__name__])
print(getattr(sys.modules[__name__],"aa"))
f = getattr(sys.modules[__name__],"method")
f()
输出如下:
E:\python\python_sdk\python.exe E:/python/py_pro/demo.py
<module '__main__' from 'E:/python/py_pro/demo.py'>
11
---method--- Process finished with exit code 0
参考
Python面试题之Python对象反射、类反射、模块反射的更多相关文章
- 千万不要错过这几道Python面试题,Python面试题No16
第1题: python下多线程的限制以及多进程中传递参数的方式? python多线程有个全局解释器锁(global interpreter lock),简称GIL,这个GIL并不是python的特性, ...
- Python面试题之Python中的类和实例
0x00 前言 类,在学习面向对象我们可以把类当成一种规范,这个思想就我个人的体会,感觉很重要,除了封装的功能外,类作为一种规范,我们自己可以定制的规范,从这个角度来看,在以后我们学习设计模式的时候, ...
- Python面试题之Python反射机制
0x00 前言 def f1(): print('f1') def f2(): print('f2') def f3(): print('f3') def f4(): print('f4') a = ...
- Python面试题之Python面试题汇总
在这篇文章中: Python基础篇 1:为什么学习Python 2:通过什么途径学习Python 3:谈谈对Python和其他语言的区别 Python的优势: 4:简述解释型和编译型编程语言 5:Py ...
- python面试题二:Python 基础题
1.位和字节的关系? Byte 字节 bit 位 1Byte = 8bit 2.b.B.KB.MB.GB 的关系? 1Byte = 8bit KB 1KB=1024B MB 1MB=1024KB GB ...
- Python面试题之Python面向对象编程汇总
面向对象的设计思想是从自然界中来的,因为在自然界中,类(Class)和实例(Instance)的概念是很自然的.Class是一种抽象概念,比如我们定义的Class——Student,是指学生这个概念, ...
- python面试题之Python支持什么数据类型?
所属网站分类: 面试经典 > python 作者:外星人入侵 链接:http://www.pythonheidong.com/blog/article/67/ 来源:python黑洞网,专注py ...
- Python面试题之Python反射详解
0x00 前言 反射,可以理解为利用字符串的形式去对象中操作成员属性和方法 反射的这点特性让我联想到了exec函数,也是把利用字符串的形式去让Python解释器去执行命令 Python Version ...
- Learn Python the hard way, ex45 对象、类、以及从属关系
#!/usr/bin/python #coding:utf-8 # animal is-a object(yes,sort of sonfusing)look at the extra credit ...
随机推荐
- poj 2914(stoer_wanger算法求全局最小割)
题目链接:http://poj.org/problem?id=2914 思路:算法基于这样一个定理:对于任意s, t V ∈ ,全局最小割或者等于原图的s-t 最小割,或者等于将原图进行 Cont ...
- java项目学习
GitHub地址:https://github.com/zhanglei-workspace/shopping-management-system
- 第五篇:使用无缓冲IO函数读写文件
前言 本文介绍使用无缓冲IO函数进行文件读写. 所谓的无缓冲是指该IO函数通过调用系统调用实现,其实系统调用内部的读写实现也是使用了缓冲技术的. 读写步骤 1. 打开文件 open 函数 2. 读写文 ...
- 72、android状态栏一体化,状态栏改变颜色
只能在4.4以上版本使用. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android&q ...
- 【BZOJ1576】[Usaco2009 Jan]安全路经Travel 最短路+并查集
[BZOJ1576][Usaco2009 Jan]安全路经Travel Description Input * 第一行: 两个空格分开的数, N和M * 第2..M+1行: 三个空格分开的数a_i, ...
- 【BZOJ1491】[NOI2007]社交网络 Floyd
[BZOJ1491][NOI2007]社交网络 Description 在社交网络(socialnetwork)的研究中,我们常常使用图论概念去解释一些社会现象.不妨看这样的一个问题. 在一个社交圈子 ...
- Audit logon events&Logon type
表一.Logon type 表二.Audit logon events 表三.Logon type details Logon type Logon title Description 2 Inter ...
- 第09章—使用Lombok插件
spring boot 系列学习记录:http://www.cnblogs.com/jinxiaohang/p/8111057.html 码云源码地址:https://gitee.com/jinxia ...
- CSS 快速入门
特点: CSS 将网页内容和显示样式进行分离,提高了显示效果的功能. CSS 和 html 相结合的四种方式: style 属性的方式 每个 html 标签中都有一个 style 样式属性, 该属性的 ...
- tomcat和jboss的区别
1. Tomcat是Apache鼎力支持的Java Web应用服务器(注:servlet容器),由于它优秀的稳定性以及丰富的文档资料,广泛的使用人群,从而在开源领域受到最广泛的青睐. 2. Jboss ...