Doubt about object orientation in Python

Asked

Viewed 95 times

0

I’m a classmate 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 way! My friend this way below, I was doubtful about the way to write and we did not come to the conclusion of the best is to do the same thing!

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

The question is, what’s the difference between using the "_" and when not using it? That wouldn’t break the concept of encapsulation?

1 answer

1


@weltonvaz character "_" was used due to python code convention proposed by pep8 (PEP8 documentation: https://www.python.org/dev/peps/pep-0008/ ). More basic way pep8 proposes as good practice of development and readability in writing python code the creation of methods and variables using the format Snake Case, where words are separated by the character _. For example, create a variable called "return all values", would be: returns all values. The method would return all().

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

In the case of your friend’s code he created the get method to return the duration attribute value 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 which case to access the values of the attributes use the get methods that return the attribute value and to set values to the used attributes-if the set methods that normally receive a parameter that are assigned to the class attribute, for example:

get_duracao(): returns the duration attribute value of its program class.

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

In the quoted code it turns out 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 program code.get_duration(), if you look at his class it is likely to look like this:

class programa:

    duracao = 0

    def get_duracao():
        return duracao

I recommend reading the concepts of object orientation to better understand these concepts I mentioned. Caelum has a free Java booklet that explains well the concepts of object orientation, however, in the java language https://www.caelum.com.br/apostila-java-orientacao-objetos/. But there is also a lot of object orientation content in python.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.