Doubt about Python classes and methods

Asked

Viewed 252 times

1

I have a question, I can’t do an exercise in classes and methods.

2 - Create the class "Date" with the attributes: day, month, and year. And create the methods "setarData(receives day, month and year)" and "print("ex: 03/08/2017")". Constructor must initialize with 01/01/1970. USE OPTIONAL PARAMETERS.

The program must start with 01/01/1970 and must print the date the user enters. Ex: 03/08/2017

Imagery: http://imgur.com/a/sFOBv

What I managed to do, I stuck to that part...:

class Data:
def __init__(self, d = 1, m = 1, a = 1970):
    self.dia = d
    self.mes = m
    self.ano = a

def setarData(self, d = 3, m = 8, a = 2017):
    self.dia = 
    self.mes = m
    self.ano = a
  • And what is the doubt?

  • I wanted your help to solve the exercise. I have many doubts about how to create classes and methods and such. And I would like help...

  • 1

    But describe what exactly you’re missing.

  • I don’t know how to go on. And I don’t even know if what I did is right

  • You don’t know how to do the imprimir()? The statement is a little weird, is that right? Even if you can understand it is a little ambiguous.

  • Yes, that’s the statement...

  • I updated the topic with the image of the exercise. It is hosted in Imgur... I hope you understand now.

  • I still don’t understand the doubt.

  • Except for the wrong indentation within the class, the method definition is correct. By the way, in the method setarData lacked the d in self.dia = d.

Show 4 more comments

1 answer

2


It seems very simple, you are almost there. Just fix an error in the method setarData(), as noted by Anderson...

def setarData(self, d = 3, m = 8, a = 2017):
    self.dia = d
    self.mes = m
    self.ano = a

And add the method imprimir():

def imprimir(self):
    print '%02d/%02d/%04' % (self.dia, self.mes, self.ano)

If I were you I would remove the optional parameters of the method setarData() because apparently it was not requested and also does not seem to me to make much sense. It would be like this:

def setarData(self, d, m, a):
    self.dia = d
    self.mes = m
    self.ano = a
  • And how would I import my class in my main program into another file . py?

  • I added a photo to the main post, take a look.

  • Put your class or method in a simple name file, without accents or hyphens and with extension .py (codigo.py, for example) and, from your main program call import codigo and d = codigo.Data() or d = codigo.Data(10, 8, 2017) and d.imprimir().

Browser other questions tagged

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