当前位置: 首页 > news >正文

python中的__dict__

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

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

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

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

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

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

class MyTestDict(object):a = 0b = 1def __init__(self):self.a = 2self.b = 3def test_func(name=None):print('I am {}'.format(name))@staticmethoddef static_test():print('static_test')@classmethoddef 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__实例化类:

print(MyTestDict.__dict__["test_func"](name='XiaoMing'))

I am XiaoMing

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

official.py文件内容:

class MyTestDict(object):a = 0b = 1def __init__(self):self.a = 2self.b = 3def test_func(name=None):print('I am {}'.format(name))@staticmethoddef static_test():print('static_test')@classmethoddef 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文件中的方法

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

I am Tom
Tom
 

python中的__dict__ - 知乎

http://www.lryc.cn/news/325756.html

相关文章:

  • 数学分析复习:无穷乘积
  • 02 React 组件使用
  • 你就是上帝
  • Spring Cloud: openFegin使用
  • 流畅的 Python 第二版(GPT 重译)(二)
  • Flutter 旋转动画 线性变化的旋转动画
  • 【Web应用技术基础】HTML(5)——案例1:展示简历信息
  • ethers.js:wallet(创建钱包,导入助记词,导入私钥)
  • 面试笔记——Java集合篇
  • 在 IntelliJ IDEA 中使用 Terminal 执行 git log 命令后的退出方法
  • 架构整洁之道-读书总结
  • 蓝桥杯学习笔记(贪心)
  • 【无标题】如何使用 MuLogin 设置代理
  • 芒果YOLOv8改进135:主干篇GCNet,统一为全局上下文建模global context结构,即插即用,助力小目标检测,轻量化的同时精度性能涨点
  • 全面:vue.config.js 的完整配置
  • 海量数据处理项目-账号微服务注册Nacos+配置文件增加
  • DNS 服务 Unbound 部署最佳实践
  • 力扣HOT100 - 42. 接雨水
  • 攻防世界-baby_web
  • 数据可视化基础与应用-04-seaborn库从入门到精通01-02
  • 学习 zustand
  • 竞赛 opencv python 深度学习垃圾图像分类系统
  • vsto worksheet中查找关键字【关键字】获取对应的整列 union成一个range
  • flask_restful规范返回值之参数设置
  • 基于java+springboot+vue实现的超市管理系统(文末源码+Lw+ppt)23-354
  • AI大模型学习:开启智能时代的新篇章
  • 【字符串】字符串哈希
  • MacOS快速安装FFmpeg、ffprobe、ffplay
  • 数据结构 之 树习题 力扣oj(附加思路版)
  • 闭包学习,闭包和高阶函数