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

相关推荐
weixin_307779131 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
ew452182 小时前
ElementUI表格表头自定义添加checkbox,点击选中样式不生效
前端·javascript·elementui
suibian52352 小时前
AI时代:前端开发的职业发展路径拓宽
前端·人工智能
Moon.92 小时前
el-table的hasChildren不生效?子级没数据还显示箭头号?树形数据无法展开和收缩
前端·vue.js·html
垚垚 Securify 前沿站2 小时前
深入了解 AppScan 工具的使用:筑牢 Web 应用安全防线
运维·前端·网络·安全·web安全·系统安全
多想和从前一样4 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
ll7788114 小时前
LeetCode每日精进:20.有效的括号
c语言·开发语言·算法·leetcode·职场和发展
工业甲酰苯胺5 小时前
Vue3 基础概念与环境搭建
前端·javascript·vue.js
小喵要摸鱼6 小时前
【Pytorch 库】自定义数据集相关的类
pytorch·python