Python - classes and methods

57 Views Asked by At

I am trying to create a class called trader that has instance attributes price, action and number, where action is an empty list and number is initially set to 0.

Within this class, i need to define a method called takeAction, so for each price, will set action equal to ‘buy’ if the price is lower than 50, ‘sell’ if the price is greater than 90, and ‘hold’ otherwise. So at each price the list action should be filled with the action that has been taken, i.e. buy, sell or hold, and number should increase by 1 if the action is ‘buy’, decrease by 1 if the action is ‘sell’ or remain constant otherwise.

My code below, does not increment the number by 1, since price is 30 so <50, I expect to increment number by 1, when I access t1.number I get the output 0. Not sure where my logic is failing, any pointer appreciated. Also just new to programming, and learning python so may have made a very obvious mistake!

class trader:
    action=[]
    number=0

    def __init__ (self,price):
        self.price=price
        
        
    def takeAction(self):
        if self.price<50:
            action.append('BUY')
            number+=1

        elif self.price>90:
            action.append('SELL')
            number = number-1

        else:
            action.append('HOLD')
            number
        return action

My instance Variable: t1=trader(30) t1.number output: 0

2

There are 2 best solutions below

0
Jab On BEST ANSWER

You should have action and number as instance values not class values. Instantiate them in the init. Then refer to them using self.

class trader:
    def __init__ (self,price):
        self.action=[]
        self.number=0
        self.price=price
        
        
    def takeAction(self):
        if self.price<50:
            self.action.append('BUY')
            self.number+=1

        elif self.price>90:
            self.action.append('SELL')
            self.number-=1

        else:
            self.action.append('HOLD')

        return self.action[-1]
0
Sem On

Correct me if i'm wrong but you have to put the action var and the number var in the init as a self.action and self.number

like this the code worked for me

class trader:


def __init__ (self,price):
    self.price=price
    self.action=[]
    self.number=0
    
    
def takeAction(self):
    if self.price<50:
        self.action.append('BUY')
        self.number+=1

    elif self.price>90:
        self.action.append('SELL')
        self.number = self.number-1

    else:
        self.action.append('HOLD')
        self.number
    return self.action


trade = trader(100)


print(trade.takeAction())

I'm also learing myself OOP on python good luck and I hope I could help!