python - 在不创建对象的情况下使用python中类的属性

标签 python class import attributes

我想知道是否可以在不从该类创建对象的情况下使用另一个文件中的类的属性,例如,如果我在 File_A 中有 Class_A 并将 Class_A 导入到 File_B 中,我是否必须将 Class_A 用作File_B 中的对象以便访问其属性?

最佳答案

最简单的方法:

In [12]: class MyClass(object):
...:         attr = 'attr value'

In [15]: MyClass.attr
Out[15]: 'attr value'

您还可以使用 __dict__ 属性:

__dict__ is the dictionary containing the class's namespace.

In [15]: MyClass.__dict__.get('attr', None)
Out[15]: 'attr value'

如果需要使用方法,请使用静态方法装饰器:

In [12]: class MyClass(object):
...:         @staticmethod
...:         def the_static_method(x):
...:             print(x)


In [15]: MyClass.the_static_method(2)
Out[15]: 2

关于python - 在不创建对象的情况下使用python中类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45000913/

相关文章:

python - AWS深度学习AMI虚拟环境激活

language-agnostic - 程序员应该在一个文件中放入多少个类?

c++ - 在默认构造函数中声明 arr 时未在此范围内声明“arr”

perl - 尝试在 Perl 中使用 Module 并在模块不可用时打印消息

python - 字符串键和整数值的基本 Python 字典

python - 自动运行 python 结果为 "EOF when reading a line "

python - 创建类 python 和 __init__ 的实例

javascript - 导入模块 typescript 错误

javascript - Angular 中 2 个导入之间的差异

python - 将字符串与另一个包含变量的字符串连接起来