我想知道是否可以在不从该类创建对象的情况下使用另一个文件中的类的属性,例如,如果我在 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/