Question about object orientation in Python

0

I'm a roommate we were doing a script I wrote my script in this way:

detalhes = programa.duracao if hasattr(programa, 'duracao') else programa.temporada

In my case, I'm calling it that! My friend in this way below, I was in doubt as to the way of writing and we did not reach the conclusion of the best way of doing the same thing!

detalhes = programa.get_duracao() if hasattr(programa, '_duracao') else programa.get_temporada()

The question is, what is the difference between using "_" and when not to use? Would not that break the encapsulation concept?

    
asked by anonymous 20.09.2018 / 14:25

1 answer

1

@weltonvaz The "_" character was used because of the python code convention proposed by pep8 (PEP8 documentation: link ). In a more basic way, pep8 proposes as good practice of development and readability in writing python code the creation of methods and variables using the Snake Case format, where words are separated by the _ character. For example, creating a variable called "return all values" would be: return_all_values ().

There are other writing styles like the Camel Case, where words are written all together, but the first letter of each word is written in capital letters. This style is very used in java, where using the same example mentioned above the writing would be: returnTypesValues ().

In the case of your friend's code he created the get method to return the value of the duration attribute of the program class. It is common in Object Oriented programming to create the getters (get) and setters (set) methods of the attributes of a class, in this case to get the values of the attributes we use the get methods that return the value of the attribute and to set values attributes are the set methods that are normally assigned a parameter that are assigned to the class attribute, for example:

get_duration (): returns the value of the duration attribute of your program class.

set_duration (1): adds value 1 to the duration attribute of the program class.

In the aforementioned code it happens that you are accessing the duration attribute of the person class directly (program.duration) and your friend used a method to return the value, so the code program.get_duration (), if you look at his class it's likely to look something like this:

class programa:

    duracao = 0

    def get_duracao():
        return duracao

I recommend reading the concepts of object orientation to better understand these concepts that I mentioned. Caelum has a free Java book that explains well the concepts of object orientation, but in the java language link . But there is also a lot of python object-oriented content.

    
20.09.2018 / 14:59