静态方法可以导入吗



在一个文件中具有调用者的类中有许多静态方法的示例。这很好用。但是我已经尝试过用staticmethod将类保存在一个文件中,并从调用方导入它。这随后抛出错误"0";AttributeError:"module"对象没有属性methodname">

我用的是python2.7。使用了Python中静态方法的确切示例?

import MyClass
# belwo class is saved in a saparate file named MyClass.py
# class MyClass(object):
#     @staticmethod
#     def the_static_method(x):
#         print(x)
MyClass.the_static_method(2)  # outputs 2
# if via import, we have the error: AttributeError: 'module' object has no attribute 'the_static_method'

在您的示例中,由于python文件(MyClass.py(的名称与类名相同,python将假定您引用的是模块MyClass(这是您的文件(,而不是类MyClass。一个建议是将第一行import MyClass更改为from MyClass import MyClass。那么它应该会起作用。通常最好遵循此处推荐的Python命名约定https://softwareengineering.stackexchange.com/questions/308972/python-file-naming-convention

最新更新