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

相关推荐
任子菲阳2 小时前
学Java第四十四天——Map实现类的源码解析
java·开发语言
听风吟丶2 小时前
Java 11+ HttpClient 实战:从 HttpURLConnection 到现代 HTTP 客户端的全面升级
java·开发语言·http
老前端的功夫2 小时前
前端Echarts性能优化:从卡顿到流畅的百万级数据可视化
前端·javascript
进击的野人2 小时前
深入解析localStorage:前端数据持久化的核心技术
前端·javascript
今晚打老虎2 小时前
c++(斗罗大陆3)
开发语言·c++·斗罗大陆3
懵圈2 小时前
第2章:项目启动 - 使用Vite脚手架初始化项目与工程化配置
前端
Mh2 小时前
如何优雅的消除“if...else...”
前端·javascript
领航猿1号2 小时前
如何通过神经网络看模型参数量?
人工智能·python·神经网络·大模型参数量
mywpython2 小时前
Python使用消息队列rabbitmq
开发语言·python·rabbitmq
火鸟23 小时前
给予虚拟成像台尝鲜版十之二,完善支持 HTML 原型模式
前端·html·原型模式·通用代码生成器·给予虚拟成像台·快速原型·rust语言