python中的__dict__

**类的__dict__**返回的是:类的静态函数、类函数、普通函数、全局变量以及一些内置的属性都是放在类的__dict__里的,

而实例化对象的:__dict__中存储了一些类中__init__的一些属性值。

**import的py文件 dict**返回的是:__init__的一些属性值 + 该py文件中的不在class中的方法(可以进行调用并得到返回值)

一、在一个py文件内调用:

可以通过__dict__访问类中的所有属性的键值对

__dict__的返回值为字典,你可以通过

python 复制代码
class MyTestDict(object):
    a = 0
    b = 1

    def __init__(self):
        self.a = 2
        self.b = 3

    def test_func(name=None):
        print('I am {}'.format(name))

    @staticmethod
    def static_test():
        print('static_test')

    @classmethod
    def class_test(cls):
        print('class_test')


myTestDict = MyTestDict()
print(MyTestDict.__dict__)
print(myTestDict.__dict__)

{'module': 'main',

'a': 0,

'b': 1,

'init': <function MyTestDict.init at 0x7f1057ed5700>,

'test_func': <function MyTestDict.test_func at 0x7f1057e00c10>,

'static_test': <staticmethod object at 0x7f1057f84cd0>,

'class_test': <classmethod object at 0x7f1057f21400>,

'dict': <attribute 'dict' of 'MyTestDict' objects>,

'weakref': <attribute 'weakref' of 'MyTestDict' objects>,

'doc': None}

{'a': 2, 'b': 3}

通过字典__dict__实例化类:

python 复制代码
print(MyTestDict.__dict__["test_func"](name='XiaoMing'))

I am XiaoMing

二、在另外一个py文件调用:

official.py文件内容:

python 复制代码
class MyTestDict(object):
    a = 0
    b = 1

    def __init__(self):
        self.a = 2
        self.b = 3

    def test_func(name=None):
        print('I am {}'.format(name))

    @staticmethod
    def static_test():
        print('static_test')

    @classmethod
    def class_test(cls):
        print('class_test')



# 如果在class外部,则在import这个py文件的时候,可以通过official.__dict__['test_func_Out'](name='Tom')来调用
def test_func_Out(name=None):
    print('I am {}'.format(name))
    return name

另外一个py文件:

这样可以调用另外py文件中的方法

python 复制代码
import official

print(official.__dict__['test_func_Out'](name='Tom'))

I am Tom

Tom

python中的__dict__ - 知乎

相关推荐
闻道且行之6 小时前
TurboOCR:基于PP-OCRv6的极速Windows离线OCR工具,深度解析3.4GB依赖背后的技术架构
c++·人工智能·python·qt·机器学习·ocr
仿生狮子7 小时前
别再说“全栈”了,AI 时代团队只认这 5 种人
前端·人工智能·后端
kyriewen7 小时前
AI 写的 React 组件,合并前必查的 6 个坏味道——每个都有代码对比
前端·javascript·react.js
许彰午7 小时前
95_Python内存管理与垃圾回收
开发语言·python
Highcharts.js7 小时前
软件开发公司为什么选择 Highcharts?
前端·前端框架·echarts·数据可视化·技术选型·highcharts·图表工具
多加点辣也没关系8 小时前
JavaScript|第13章:原始类型的方法
开发语言·javascript·ecmascript
এ慕ོ冬℘゜8 小时前
深入理解 JavaScript 事件体系:Window、鼠标与键盘事件详解
开发语言·javascript·okhttp
骄阳如火8 小时前
Python 性能深度剖析:从“被诟病的慢”到“Rust 重塑”的拐点
python
阿祖zu8 小时前
企业 AI 转型之痛,个人提效十倍不止,组织效率仍止步不前?
前端·aigc·agent
满怀冰雪8 小时前
03-第一个 Paddle 程序:Tensor 创建、计算与设备管理
人工智能·python·paddle