本节内容

  1. 概述
  2. 反射函数
  3. 综合使用

一、概述

  反射我们以后会经常用到,这个东西实现了动态的装配,通过字符串来反射类中的属性和方法

二、反射函数

2.1 hasarttr(obj,name_str)

作用:判断一个对象obj中是否有对应的name_str字符串的属性或者方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    def eat(self,food):
        print("{0} is eating...{1}".format(self.name,food))
 
= Dog("shabi")
choice = input(">>>:").strip()
 
print(hasattr(d,choice))  #obj中是否有对应的choice字符串的属性或者方法
 
#输出
>>>:name  #输入对象存在属性
True
>>>:eat  #输入对象存在的方法
True

2.2 getattr(obj,name_str)

作用:根据字符串name_str获取obj对象中的对应方法的内存地址或者对应属性的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    def eat(self,food):
        print("{0} is eating...{1}".format(self.name,food))
 
= Dog("shabi")
choice = input(">>>:").strip()
 
print(getattr(d,choice))  #choice获取obj对象中的对应方法的内存地址或者对应属性的值
 
#输出
>>>:name  #返回name属性的值
shabi
>>>:eat
<bound method Dog.eat of <__main__.Dog object at 0x00000157A129CF28>>  #返回eat方法的内存地址

2.3 setattr(x,y,z)

作用:给obj对象添加一个新属性或者新方法,setattr(x, 'y', v) is equivalent to ``x.y = v''

①给对象新增一个新方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def bulk(self):  #先定义一个bulk函数
    print("{0} is yelling...".format(self.name))
 
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    def eat(self,food):
        print("{0} is eating...{1}".format(self.name,food))
 
= Dog("shabi")
choice = input(">>>:").strip()
 
setattr(d,choice,bulk)  #输入的是talk,所以又等同于d.talk = bulk
#d.talk(d) 直接写死,用d.talk(d),一般不这么写
func = getattr(d,choice) #用getattr来获取
func(d)
 
#输出
>>>:talk
shabi is yelling...

②给对象新增一个属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    def eat(self,food):
        print("{0} is eating...{1}".format(self.name,food))
 
= Dog("shabi")
choice = input(">>>:").strip()
 
setattr(d,choice,22)  #输入的是age,所以又等同于d.age = 22
# print(d.age) 这样就写死了,还是用下面一种
print(getattr(d,choice))
 
#输出
>>>:age
22

2.4  delattr(x,y)

作用:删除obj对象中的属性或者方法,delattr(x, 'y') is equivalent to ``del x.y''

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    def eat(self,food):
        print("{0} is eating...{1}".format(self.name,food))
 
= Dog("shabi")
choice = input(">>>:").strip()
 
delattr(d,choice) #根据字符串删除属性或者方法
print(d.name)
print(d.eat)
 
#输出
>>>:name   #删除属性name
Traceback (most recent call last):
  File "E:/PycharmProjects/pythontest/day7/反射/反射.py", line 22in <module>
    print(d.name)
AttributeError: 'Dog' object has no attribute 'name'
>>>:eat   #删除方法eat
Traceback (most recent call last):
  File "E:/PycharmProjects/pythontest/day7/反射/反射.py", line 21in <module>
    delattr(d,choice)
AttributeError: eat

三、综合使用

3.1 综合使用hasattr、getattr、setattr

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    def eat(self,food):
        print("{0} is eating...{1}".format(self.name,food))
 
= Dog("shabi")
choice = input(">>>:").strip()
 
if hasattr(d,choice):  #判断d对象中存在属性和方法
    name_value = getattr(d,choice)  #获取属性值
    print(name_value)
    setattr(d,choice,"hong")   #修改属性值
    print(getattr(d,choice))   #重新获取属性的值
else:
    setattr(d,choice,None)    #设置不存在的属性值为None
    = getattr(d,choice)
    print(v)
 
#输出
>>>:name
shabi
hong
>>>:abc
None

面向对象【day08】:反射(五)的更多相关文章

  1. Python 面向对象之反射

    Python 面向对象之反射 TOC 什么是反射? hasattr getattr setattr delattr 哪些对象可以使用反射 反射的好处 例子一 例子二 什么是反射? 程序可以访问.检查和 ...

  2. Python之面向对象进阶------反射(Day26)

    一 classmethod class Classmethod_Demo(): role = 'dog' @classmethod def func(cls): print(cls.role) Cla ...

  3. python 面向对象之反射及内置方法

    面向对象之反射及内置方法 一.静态方法(staticmethod)和类方法(classmethod) 类方法:有个默认参数cls,并且可以直接用类名去调用,可以与类属性交互(也就是可以使用类属性) 静 ...

  4. 百万年薪python之路 -- 面向对象之 反射,双下方法

    面向对象之 反射,双下方法 1. 反射 计算机科学领域主要是指程序可以访问.检测和修改它本身状态或行为的一种能力(自省) python面向对象中的反射:通过字符串的形式操作对象相关的属性.python ...

  5. SOLID:面向对象设计的五个基本原则

    在程序设计领域,SOLID 是由罗伯特·C·马丁在 21 世纪早期引入的记忆术首字母缩略字,指代了面向对象编程和面向对象设计的五个基本原则.当这些原则被一起应用时,它们使得一个程序员开发一个容易进行软 ...

  6. Python面向对象之-反射

    Python中一切皆对象,在Python中的反射:通过字符串的形式操作对象的属性 hasattr  判断是否有改属性或者方法,有返回True,没有返回false getattr  如果是属性获得该属性 ...

  7. 面向对象之反射 与__str__等内置函数

    一  反射 1.面向对象中的反射:通过字符串的形式操作对象的相关属性,python中一切事物都是属性(都可以使用反射) 四个可以实现自省<反射>的函数:hasattr /  getattr ...

  8. day28 面向对象:反射,内置函数,类的内置方法

    面向对象进阶博客地址链接: http://www.cnblogs.com/Eva-J/articles/7351812.html 复习昨日内容: # 包 # 开发规范 # # hashlib # 登录 ...

  9. python基础之 面向对象之反射

    1.isinstance和issubclass issubclass(Son,Foo) 判断雷与类之间的是否有继承关系,接受两个参数,一个是疑似子类,一个是疑似父类,判断Son是否是Foo的子类 ob ...

  10. C++面向对象高级编程(五)类与类之间的关系

    技术在于交流.沟通,转载请注明出处并保持作品的完整性. 本节主要介绍一下类与类之间的关系,也就是面向对象编程先介绍两个术语 Object Oriented Programming   OOP面向对象编 ...

随机推荐

  1. git使用命令记录

    一,两个概念:1.工作区:你电脑里能看见的目录,比如一个项目文件夹就是一个工作区2.版本库工作区(该项目的文件夹)中有一个隐藏文件 .git ,就是git的版本库.(这个文件默认是隐藏,Ctrl+h ...

  2. JVM EXCEPTION_ACCESS_VIOLATION

    ## A fatal error has been detected by the Java Runtime Environment:## EXCEPTION_ACCESS_VIOLATION (0x ...

  3. 将J2EE的Web项目设置为支持Activiti

    <natures> <nature>org.eclipse.jem.workbench.JavaEMFNature</nature> <nature>o ...

  4. Classification Truth Table

    在机器学习中对于分类结果的描述,一般有四种:true positive, true negative, false positive 和 false negative. Precision, Reca ...

  5. intval()和int()

    int intval ( mixed $var [, int $base ] )    通过使用特定的进制转换(默认是十进制),参数base表示进制,只有当var是字符串时,base才会有意义,表示按 ...

  6. 英国电信反悔华为是唯一真正的5G供应商

    导读 英国电信反悔华为是唯一真正的5G供应商 英国电信的一位发言人表示,该公司目前正「从我们自 2006 年以来实施的网络架构原则中,从我们的 3G 和 4G 网络核心提取华为设备」. 英国电信已经不 ...

  7. BZOJ3786星系探索——非旋转treap(平衡树动态维护dfs序)

    题目描述 物理学家小C的研究正遇到某个瓶颈. 他正在研究的是一个星系,这个星系中有n个星球,其中有一个主星球(方便起见我们默认其为1号星球),其余的所有星球均有且仅有一个依赖星球.主星球没有依赖星球. ...

  8. BZOJ2157旅游——树链剖分+线段树

    题目描述 Ray 乐忠于旅游,这次他来到了T 城.T 城是一个水上城市,一共有 N 个景点,有些景点之间会用一座桥连接.为了方便游客到达每个景点但又为了节约成本,T 城的任意两个景点之间有且只有一条路 ...

  9. poj1068 【模拟】

    Let S = s1 s2...s2n be a well-formed string of parentheses. S can be encoded in two different ways:  ...

  10. Codeforces Round #382 (Div. 2) C. Tennis Championship

    C. Tennis Championship time limit per test 2 seconds memory limit per test 256 megabytes input stand ...