python getattr调用自己模块_Python getattr()函数使用方法代码实例

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

1: 可以从类中获取属性和函数

新建test.py文件,代码如下:

# encoding:utf-8

import sys

class GetText():

def __init__(self):

pass

@staticmethod

def A():

print("this is a staticmethod function")

def B(self):

print("this is a func")

c = "cc desc"

if __name__ == '__main__':

print(sys.modules[__name__]) #

print(GetText) #

# 获取函数

print(getattr(GetText, "A")) #

# 获取函数返回值

getattr(GetText, "A")() # this is a staticmethod function

getattr(GetText(), "A")() # this is a staticmethod function

print(getattr(GetText, "B")) #

# 非静态方法不可用

# getattr(GetText, "B")()

getattr(GetText(), "B")() # this is a func

print(getattr(GetText, "c")) # cc desc

print(getattr(GetText(), "c")) # cc desc

2:从模块中获取类(通过类名字符串得到类对象)

新建test1.py,代码如下:

#encoding:utf-8

import sys

import test

print(sys.modules[__name__])

# 从模块中获取类对象

class_name = getattr(test, "GetText")

print(class_name) #

# 调用类的属性和函数

print(getattr(class_name, "A")) #

# 获取函数返回值

getattr(class_name, "A")() # this is a staticmethod function

getattr(class_name(), "A")() # this is a staticmethod function

print(getattr(class_name(), "B")) # >

# getattr(class_name, "B")() 非静态方法不可用

getattr(class_name(), "B")() # this is a func

# 获取属性值

print(getattr(class_name, "c")) # cc desc

print(getattr(class_name(), "c")) # cc desc

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值