Why can not I pass a parameter to the class?

2

I'm trying to pass the "ink" parameter to the "Pen" class but I can not. I've tried using Boolean expressions instead of index, but still no results. Could someone give me a help ?

class Caneta():

    açao = 'escrever'

    def __init__(self, tinta):
        self.tinta = tinta

    def NivelTinta(tinta):
        rng = range(0,100)

        for tinta in rng:
            if tinta in rng[5:100]:
                print('A caneta está boa')
                break
            elif tinta in rng[1:4]:
                print('A caneta está falhando')
                break
            else:
                print('A tinta acabou')
                break

CanetaAzul = Caneta(50)

CanetaAzul.NivelTinta()

Every time I run the code, "The ink is gone" appears, and "The pen is good" should appear, because the parameter I set is "50".

    
asked by anonymous 02.10.2016 / 20:50

1 answer

2

There is a bit of logic missing from your code, as well as having a certain error.

First, you are not getting tinta as a parameter, and this is not necessary since the value is already saved in the object. You are getting self as the parameter (which is the object itself). So instead of trying to directly access tinta , you need to access the tinta property that is inside the parameter (also called %

In this case, I changed the name to tinta just to avoid confusion.

Second, this loop is completely unnecessary. You do not need to to find out if the ink level is within a certain range, you just need to use the logical comparators self and < (greater than).

Another important thing, even if loop is needed, the > statement causes the code to " ", this means that the conditions will be evaluated only once and after that the loop is stopped.

I made an adaptation in your code and now it is functional.

class Caneta():

    acao = 'escrever'

    def __init__(self, tinta):
        self.tinta = tinta

    def NivelTinta(self):
        print(self.tinta)

        if(1 <= self.tinta <= 5):
            print('A caneta esta falhando')
        elif(5 < self.tinta <= 100):
            print('A caneta esta boa')
        else:
            print('A tinta acabou')

CanetaAzul = Caneta(50)
CanetaAzul.NivelTinta()
    
02.10.2016 / 21:09