cherrun
cherrun

Reputation: 2142

Correct use of static methods

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?

Upvotes: 5

Views: 3887

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 600041

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 whatever and generateChars into 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 Password module, you still need to refer to the PasswordHelper class:

Password.PasswordHelper.generateChars(3)

Alternatively, you can import the PasswordHelper class:

from Password import PasswordHelper
...
PasswordHelper.generateChars(3)

Finally, please follow PEP8 for your module, class and function names.

Upvotes: 9

Martijn Pieters
Martijn Pieters

Reputation: 1124778

You defined the function in a class, so you need to reference it with the classname too:

print Password.PasswordHelper.generateChars(3)

Alternatively, move the function out of the class definition, at which point you do not need to use @staticmethod at all:

import random                                                                    

CHARS = "ABC"

def generateChars(length):                                                    
    return ''.join(random.choice(CHARS) for x in range(length))

In Python, functions do not have to be part of a class definition.

Upvotes: 2

Related Questions