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__ - 知乎

相关推荐
银-豆豆13 小时前
Python爬虫
开发语言·爬虫·python
webkubor13 小时前
一次前端生产白屏复盘:旧 HTML、Hash 资源和 MIME type text/html
前端·前端工程化
zmzb010314 小时前
C++课后习题训练记录Day179
开发语言·c++
咩咩啃树皮14 小时前
第63篇【终极整合巨作】从零手写原生中后台管理系统|整合62篇全部前端知识点|从头到尾完整架构+全功能逻辑
前端·架构
香吧香14 小时前
Python 基础语法总结
python
IT小盘14 小时前
10-使用Reranker提升RAG回答准确率
人工智能·python
jjjava2.014 小时前
MyBatis动态if/trim/where/set标签详解
java·开发语言·数据库
卷无止境14 小时前
Python 装饰器:给函数穿件"外套",到底难在哪?
后端·python
不正经学生14 小时前
C语言指针进阶:const 和野指针——给指针加锁,向野指针宣战
c语言·开发语言·c++·算法·c#
程序喵大人14 小时前
【C++进阶】STL算法与函数对象 - 01 让算法去处理一段迭代器范围
开发语言·c++·算法·函数对象