Object-oriented programming exercise in Python

Asked

Viewed 840 times

-1

I started studying object-oriented programming in Python this week and did an exercise but I don’t know if it’s right. I need someone to take a look at it to point out my mistakes because although the code is working, it is different from what appears in the feedback. Here is the exercise:

Square Class: Create a class that models a square:

Attributes: Side Size

Methods: Change Side Value, Return Side Value, and Calculate Area.

class Quadrado():
    def __init__(self, x):
        self.tamanho_lado = x
    def mudar_val_lado(self, novo_lado):
        x = novo_lado
        self.tamanho_lado = novo_lado
    def retorna_val_lado(self, x):
        self.tamanho_lado = x
        print(x)
    def calc_area(self, x):
        self.tamanho_lado = x
        print(x*x)

carreau = Quadrado(5)
print(carreau.tamanho_lado)

carreau.mudar_val_lado(4)
print(carreau.tamanho_lado)

carreau.retorna_val_lado(3)

carreau.calc_area(5)

2 answers

0

Why all methods receive x and change the property tamanho_lado? If there is a method mudar_val_lado, all amendments should be made solely and exclusively by him

A function retorna_val_lado should return something, right? Whatever is done with the return should stay out of the class. The same goes for calc_area. What if now, in addition to doing this, you needed to calculate the sum of the areas? You would have to have a new method that calculates the area and then adds up, if your method only returns the value of the calculation, you can do whatever you want with it, not only print onscreen

There may be cases where you want to do what you’re doing, but they’re rare and it doesn’t look like one of them

  • Thanks for the tips. I tried to avoid the mistakes that were pointed out.

-3

class Quadrado():
    def __init__(self, x):
        self.tamanho_lado = x

    def mudar_val_lado(self, novo_lado):
        x = novo_lado
        self.tamanho_lado = x

    def retorna_val_lado(self):
        print(self.tamanho_lado)

    def calc_area(self):
        self.tamanho_lado = self.tamanho_lado*self.tamanho_lado
        print(self.tamanho_lado)
  • 1

    Besides not explaining what was done, this code does not make sense. Why mudar_val_lado sets the value of x and then use in tamanho_lado? Why retorna_val_lado displays the value on the side instead of returning it? Why calc_area saves the value of the area in self.tamanho_lado and why he displays the result instead of returning it?

Browser other questions tagged

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