1

I am wondering about this question for a while and still not sure about the appropriate answer. If there is somewhere good answer already, sorry for that.

When is the good use case to use function or variable defined somewhere in module within the class instead of defining it inside as method/attribute?

Example:

PATH_TO_DIR = "abc\\def"

class Reader:
    def __init__(self, file_name):
        self.file_name = file_name

    def read_file(self):
        return pd.read_excel(os.path.join(PATH_TO_DIR, self.file_name))

or

class Reader:
    PATH_TO_DIR = "abc\\def"

    def __init__(self, file_name):
        self.file_name = file_name

    def read_file(self):
        return pd.read_excel(os.path.join(self.PATH_TO_DIR, self.file_name))

The same problem is bothering me regarding function/method, for example we could define read_file() function and use it within class externally.

I feel like defining it as method/attribute make more sense, but I have seen a lot of codes where those parts was defined externally.

I would like to know the answer regarding good practices of python programming - I know that language is able to handle a lot of strange things, but its not the case ;)

0

2 Answers 2

2

I would lean towards option 3: pass the correct absolute path to Reader.__init__. The job of Reader, presumably, is to parse a file, not worry about file-system layout.

PATH_TO_DIR = "abc\\def"

class Reader:
    def __init__(self, file_name):
        self.file_name = file_name

    def read_file(self):
        return pd.read_excel(self.file_name)


r = Reader(os.path.join(PATH_TO_DIR, "foo.xl"))
Sign up to request clarification or add additional context in comments.

Comments

1

I believe, that a good practice is to have it defined externally, because in that way you could reuse this function more easily. Also, you can reuse the same variable in other functions/classes. In your first example you are defining variable that could be used in multiple classes. Also the same class could be imported by other script that you did not design for. In second example - you can use this variable only in this function and if you want to reuse this function somewhere else - you have to overwrite this variable after initialization. And this means running __init__() method.

Personally, I avoid defining variables inside classes and functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.