在 python 中使用类的属性而不创建对象

Chr*_*owe 1 python import attributes class

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

Say*_*yPy 5

最简单的方法:

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

In [15]: MyClass.attr
Out[15]: 'attr value'
Run Code Online (Sandbox Code Playgroud)

您也可以使用 __dict__ 属性:

__dict__ 是包含类命名空间的字典。

In [15]: MyClass.__dict__.get('attr', None)
Out[15]: 'attr value'
Run Code Online (Sandbox Code Playgroud)

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

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


In [15]: MyClass.the_static_method(2)
Out[15]: 2
Run Code Online (Sandbox Code Playgroud)