Python getatter() 通过方法名字符串调用方法

____tz_zs

getatter()

getattr()这个方法最主要的作用是实现反射机制。也就是说可以通过字符串获取方法实例。这样,你就可以把一个类可能要调用的方法放在配置文件里,在需要的时候动态加载。

1、从类中获取函数和属性

获取函数

my_getatter.py

import sys


class GetatterTest(object):
    def __init__(self):
        pass

    @staticmethod
    def aa():
        print("aa staticmethod fun")

    def bb(self):
        print("bb fun")

    cc = "cc attribute"


if __name__ == '__main__':
    print(sys.modules[__name__])
    print(GetatterTest)
    """
    <module '__main__' from '/home/xxx/tzzs/mytz/my_getatter.py'>
    <class '__main__.GetatterTest'>
    """

    print(getattr(GetatterTest, "aa"))
    getattr(GetatterTest, "aa")()
    print(getattr(GetatterTest(), "aa"))
    getattr(GetatterTest(), "aa")()
    """
    <function aa at 0x7f85d5c62c08>
    aa staticmethod fun
    <function aa at 0x7f85d5c62c08>
    aa staticmethod fun
    """

    print(getattr(GetatterTest(), "bb"))
    getattr(GetatterTest(), "bb")()

    """
    <bound method GetatterTest.bb of <__main__.GetatterTest object at 0x7f85e3c4fc50>>
    bb fun
    """

获取属性

my_getatter.py

import sys


class GetatterTest(object):
    def __init__(self):
        pass

    @staticmethod
    def aa():
        print("aa staticmethod fun")

    def bb(self):
        print("bb fun")

    cc = "cc attribute"


if __name__ == '__main__':
    print(sys.modules[__name__])
    print(GetatterTest)
    """
    <module '__main__' from '/home/xxx/tzzs/mytz/my_getatter.py'>
    <class '__main__.GetatterTest'>
    """

    print(getattr(GetatterTest, "cc"))
    print(getattr(GetatterTest(), "cc"))

    """
    cc attribute
    cc attribute
    """

2、从模块获取类

通过类名字符串得到类对象
my_getatter2.py

#!/usr/bin/python2.7
# -*- coding:utf-8 -*-

import sys
import my_getatter

print(sys.modules[__name__])  # <module '__main__' from '/home/xxx/tzzs/mytz/my_getatter2.py'>

# 从模块中获取类对象
class_name = getattr(my_getatter, "GetatterTest")
print(class_name)  # <class 'my_getatter.GetatterTest'>
print(class_name())  # <my_getatter.GetatterTest object at 0x7f38a2b36490>

# 调用类的属性和函数,同上例。
print(getattr(class_name, "aa"))
getattr(class_name, "aa")()
print(getattr(class_name(), "aa"))
getattr(class_name(), "aa")()
"""
<function aa at 0x7fd6047edc08>
aa staticmethod fun
<function aa at 0x7fd6047edc08>
aa staticmethod fun
"""

print(getattr(class_name(), "bb"))
getattr(class_name(), "bb")()

"""
<bound method GetatterTest.bb of <my_getatter.GetatterTest object at 0x7fd6128d1490>>
bb fun
"""

print(getattr(class_name, "cc"))
print(getattr(class_name(), "cc"))
"""
cc attribute
cc attribute
"""
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值