【python3基础学习】【第7周】反射



一、反射概念

  • 通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法:
  1. getattr(__o, name, __default)
  2. hasattr(__object, __name)
  3. setattr(__obj, __name, __value)
  4. delattr(__obj, __name)

二、反射方法详解

1. hasattr(__object, __name)

  • Return whether the object has an attribute with the given name.
  • 判断对象是否有指定方法或属性

hasattr(__object, __name) 参数详解:

  • __object:
  1. 对象名
  • __name:
  1. 方法名
  2. 实例变量名
  3. 类变量名
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
class Cat(object):
    cat_type = "Meiduan"

    def __init__(self, name, age):
        self.name = name
        self.age = age

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


if __name__ == '__main__':
    cat = Cat("Huajuan", 2)

    # 检查方法名
    print(hasattr(cat, "eat"))
    # 检查实例变量
    print(hasattr(cat, "name"))
    print(hasattr(cat, "age"))
    # 检查类变量
    print(hasattr(cat, "cat_type"))
    # 检查没有的属性, 猫咪重量cat_weight
    print(hasattr(cat, "cat_weight"))

# 输出:
True
True
True
True
False

2. getattr(__o, name, __default)

  • Get a named attribute from an object; getattr(x, ‘y’) is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn’t
    exist; without it, an exception is raised in that case.
  • 主要用于调用函数/变量;

getattr(__o, name, __default) 参数详解:

  • __o:
  1. 对象名
  • name:
  1. 方法名
  2. 实例变量名
  3. 类变量名
  • __default:
  1. getattr(x, ‘y’) 调用时:如果指定name的1. 方法名、 2. 实例变量名、3. 类变量名均不存在,则会产生异常AttributeError;
  2. getattr(x, ‘y’, ‘Mason’) 调用时:如果指定name的1. 方法名、 2. 实例变量名、3. 类变量名均不存在,则会返回__default中给定值;
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
class Cat(object):
    cat_type = "Meiduan"

    def __init__(self, name, age):
        self.name = name
        self.age = age

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


if __name__ == '__main__':
    cat = Cat("Huajuan", 2)

    # 调用类中方法
    getattr(cat, "eat")(cat)

    # 调用实例变量
    print(getattr(cat, "name"))
    print(getattr(cat, "age"))

    # 调用类变量
    print(getattr(cat, "cat_type"))

    # getattr调用时传__default, __default可以是方法、可以是任意数据类型数据, 此处以字符串为例
    print(getattr(cat, "cat_weight", "5kg"))
    # 如果不传__default参数, 且传的name在类中不存在, 则会产生异常AttributeError
    print(getattr(cat, "cat_weight"))

# 输出:
Huajuan is eating... <__main__.Cat object at 0x000002503E29CFD0>
Huajuan
2
Meiduan
5kg
Traceback (most recent call last):
  File "D:\Codes\s14_python3\oop_learning.py", line 30, in <module>
    print(getattr(cat, "cat_weight"))
AttributeError: 'Cat' object has no attribute 'cat_weight'

3. setattr(__obj, __name, __value)

  • setattr(x, ‘y’, v) is equivalent to "x.y = v’’;
  • 主要用于设置函数/变量;

setattr(__obj, __name, __value)参数详解:

  • __obj:
  1. 对象名
  • __name:
  1. 方法名
  2. 实例变量名
  3. 类变量名
  • __value:
  1. 具体函数/变量值;
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
class Cat(object):
    cat_type = "Meiduan"

    def __init__(self, name, age):
        self.name = name
        self.age = age

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


if __name__ == '__main__':
    cat = Cat("Huajuan", 2)

    # 查看当前对象是否有"cat_weight"属性
    print(hasattr(cat, "cat_weight"))

    # 使用setattr设置cat_weight属性
    setattr(cat, "cat_weight", "5kg")

    # 查看当前对象是否有"cat_weight"属性
    if hasattr(cat, "cat_weight"):
        # 使用getattr调用cat_weight属性
        print(getattr(cat, "cat_weight"))

# 输出:
False
5kg

4. delattr(__obj, __name)

  • delattr(x, ‘y’) is equivalent to "del x.y’’;
  • 主要用于删除函数/变量;

delattr(__obj, __name)参数详解:

  • __obj:
  1. 对象名
  • __name:
  1. 方法名
  2. 实例变量名
  3. 类变量名
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
class Cat(object):
    cat_type = "Meiduan"

    def __init__(self, name, age):
        self.name = name
        self.age = age

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


if __name__ == '__main__':
    cat = Cat("Huajuan", 2)

    # 调用当前对象的"name"属性
    print(getattr(cat, "name"))

    # 删除当前对象的"name"属性
    delattr(cat, "name")

    # 再次调用当前对象的"name"属性, 由于已经删除name属性, 所以会报AttributeError异常
    print(getattr(cat, "name"))

# 输出:
Traceback (most recent call last):
  File "D:\Codes\s14_python3\oop_learning.py", line 25, in <module>
    print(getattr(cat, "name"))
AttributeError: 'Cat' object has no attribute 'name'
Huajuan
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值