0

Say I got a simple class with one public and one private method. If I call the private method in the public method - should it return a value, or should that value be set as a field in my object, for example,

class Test:
    def __init__(self, path):
        self.path = path
    def __getNoOfFiles(self):
       'count files in self.path'
       return no_of_files
    def readDir(self)
        ...
        no_of_files = __getNoOfFiles()

or

class Test:
    def __init__(self, path):
        self.path = path
        self.no_of_files = 0
    def __getNoOfFiles(self):
       self.no_of_files = 'count files in self.path'
    def readDir(self)
        __getNoOfFiles()
        no_of_files = self.no_of_files
4

4 に答える 4

2

IMO, getters and setters should be public; i.e., do not precede the method's signature with a double underscore. Also in Python, the value is usually simply accessed if it's meant to be used out of that particular class instance.

Discussions about the utility of getters and setters should help you more in your first OOP steps; you can start by reading this question.

于 2012-10-01T12:54:26.790 に答える
1

You can do it either way... It doesn't make much of a difference... (But one important difference is that, in second case, you are creating an extra instance attribute for your instance... If you want it to be used in other methods, then this is appropriate).

Also, you don't need to create a local variable in your public method to use the instance attribute created... You can directly access that instance attribute...

You don't need to do this in a public method in the second case:

no_of_files = self.no_of_files

You can just access your instance attribute directly...

And you should call your method on self instance... You can't call it just by its name...

So, you should replace:

__getNoOfFiles()

with:

self.__getNoOfFiles()

And __getNoOfFiles() is not as Pythonic as __get_no_of_files() - just a suggestion.

于 2012-10-01T12:52:02.537 に答える
1

It makes little difference in most circumstances, but there are minor reasons for choosing one way or the other. If the value is likely to be used more than once and it costs something to compute, it may be helpful to cache it in the class instance. But classes often include methods that do nothing but return values from the instance, so the return-value option fits with that style.

In general, whatever looks better to your eye.

于 2012-10-01T12:58:52.657 に答える
0

It's really up to you. If you going to need no_of_files outside readDir, it might be worth saving it. If not...

Note that in your examples, you should use no_of_files = self.__getNoOfFiles(): you need the self before the method.

于 2012-10-01T12:52:22.133 に答える