DEV Community

Discussion on: Day 20 Of 100DaysofCode: Writing a OOP code To Read Text File And Find Number Of Word

Collapse
 
hentaichan profile image
ヘンタイちゃん • Edited

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

def __init__(self,filename = None):
        self.file = open(filename)
        self.lines = [line.strip() for line in self.file.readlines()]
        self.numbers = []
        self.words = []
        self.num_occur = {}
        self.word_occur = {}
Enter fullscreen mode Exit fullscreen mode

in your constructor. (Notice that without changing any of your code you could also have written

print(fileH.words)
print(fileH.numbers)
print(fileH.num_occur)
print(fileH.word_occur)
Enter fullscreen mode Exit fullscreen mode

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.

Thread Thread
 
iamdurga profile image
Durga Pokharel

Thank you very much

Thread Thread
 
hentaichan profile image
ヘンタイちゃん

You're welcome!