0

there are many examples of staticmethod in a class with caller in one file. this works fine. but i have tried to save the class with staticmethod in a single file and import it from caller. this then throws the error "AttributeError: 'module' object has no attribute methodname"

i am using python2.7. used exact example from Static methods in 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'
martineau
  • 119,623
  • 25
  • 170
  • 301
sshen
  • 3
  • 3
  • It has nothing to do with `staticmethod`. Notice how the error message says `'module' object`? Notice how you are trying to use something that is part of a class? Which do you `import` when you use the `import` statement: modules, or classes? Now - is your class perhaps accessible from the module? So.... – Karl Knechtel Oct 17 '20 at 06:55

1 Answers1

3

In your example, since the name of the python file (MyClass.py) is the same as the class name, Python will assume you are referring to the module MyClass(which is your file) instead of the class MyClass. One suggestion is to change your first line import MyClass to from MyClass import MyClass. Then it should work. It's generally better to follow the Python naming convention recommended here https://softwareengineering.stackexchange.com/questions/308972/python-file-naming-convention

H.T. Kong
  • 151
  • 5