Something I would suggest: It's more natural to think of words and numbers as properties of a file (handler) instead of methods, e.g.
@propertydefwords(self):total=[]# rest of your code comes here
That way, you can access these properties by print(file_handler.words). Also notice that I don't use camel case for variable names (fileH -> file_handler is easier to read in my opinion)
You can use this trick to remember when to declare something as a property, and when as a (static) method:
Can this thing you want to implement be described in terms of actions (e.g. read_file or write_file) or is it a descriptive characteristic (e.g. file_name or file_size)? In general, if you have a method that takes no arguments (other than self) in an OOP class, chances are you should declare this as an property.
But there are a few more differences you might not be aware of: for example you also wrote
which would also have returned the same result. These are also properties! But they're not readonly, i.e. once an FileHandler object is instantiated, a client could (by accident) override fileH.words = ['hello', 'world'] (or any other list) which could be an issue if this results in unexpected behavior later. This list should not change unless the original file is modified. Therefore, by using the @property decorator you declare your properties as readonly and prevent these sort of mistakes.
Something I would suggest: It's more natural to think of
words
andnumbers
as properties of a file (handler) instead of methods, e.g.That way, you can access these properties by
print(file_handler.words)
. Also notice that I don't use camel case for variable names (fileH -> file_handler
is easier to read in my opinion)Thank you for suggestion
You can use this trick to remember when to declare something as a property, and when as a (static) method:
Can this thing you want to implement be described in terms of actions (e.g.
read_file
orwrite_file
) or is it a descriptive characteristic (e.g.file_name
orfile_size
)? In general, if you have a method that takes no arguments (other thanself
) in an OOP class, chances are you should declare this as an property.But there are a few more differences you might not be aware of: for example you also wrote
in your constructor. (Notice that without changing any of your code you could also have written
which would also have returned the same result. These are also properties! But they're not readonly, i.e. once an
FileHandler
object is instantiated, a client could (by accident) overridefileH.words = ['hello', 'world']
(or any other list) which could be an issue if this results in unexpected behavior later. This list should not change unless the original file is modified. Therefore, by using the@property
decorator you declare your properties as readonly and prevent these sort of mistakes.Thank you very much
You're welcome!