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

相关推荐
一晌小贪欢5 分钟前
Python爬虫第7课:多线程与异步爬虫技术
开发语言·爬虫·python·网络爬虫·python爬虫·python3
IT_陈寒8 分钟前
Redis 性能翻倍的 5 个隐藏技巧,99% 的开发者都不知道第3点!
前端·人工智能·后端
ftpeak14 分钟前
《Cargo 参考手册》第二十二章:发布命令
开发语言·rust
街尾杂货店&16 分钟前
css word属性
前端·css
luckyPian28 分钟前
学习go语言
开发语言·学习·golang
祁同伟.1 小时前
【C++】多态
开发语言·c++
fruge2 小时前
2025前端工程化与性能优化实战指南:从构建到监控的全链路方案
前端·性能优化
朱嘉鼎2 小时前
C语言之可变参函数
c语言·开发语言
yanxing.D2 小时前
OpenCV轻松入门_面向python(第六章 阈值处理)
人工智能·python·opencv·计算机视觉
JJJJ_iii4 小时前
【机器学习01】监督学习、无监督学习、线性回归、代价函数
人工智能·笔记·python·学习·机器学习·jupyter·线性回归