I have following simplified class named Password.py in folder1:
import random
CHARS = "ABC"
class PasswordHelper(object):
@staticmethod
def generateChars(length):
return ''.join(random.choice(CHARS) for x in range(length))
Now I have another class TestClass.py in folder2:
sys.path.append('../folder1/')
import Password
class Tester:
def whatever(self):
print Password.generateChars(3)
def main():
x = Tester()
x.whatever()
# call main method
main()
When calling python TestClass.py I get the following error: AttributeError: ‘module’ object has no attribute ‘generateChars’. Both folders are on the same level. Is there a problem with the way I import the class files or with the static method declaration itself?
Python is not Java.
Firstly, there is absolutely no point to either the Tester or the Password classes. If you’re not storing state, then don’t define a class. Make both
whateverandgenerateCharsinto normal standalone functions.However, assuming you’re doing this just to learn about Python classes, you have not understood that a class does not equal a module in Python. Since you’ve imported the
Passwordmodule, you still need to refer to thePasswordHelperclass:Alternatively, you can import the PasswordHelper class:
Finally, please follow PEP8 for your module, class and function names.