0

Hello I ve a stupid pb that stucks me, I don t understand why the str argument in not taken into account :

Here is tst.py:

class CurrenciPair():

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

        def displayCount(self):
            histo = market_pair
            print(market_pair)      

Outside the class:

def reco(market_pair):
        print(market_pair)
        emp = CurrenciPair(market_pair)
        emp.displayCount()

Here is test.py that import the previous file:

import tst as tt

market = 'TEST'
tt.reco(market)

Here is the result:

>>python test.py
TEST
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    tt.reco(market)
  File "C:\Users\or2\Downloads\crypto\API\python_bot_2\tst.py", line 19, in reco
    emp.displayCount()
  File "C:\Users\or2\Downloads\crypto\API\python_bot_2\tst.py", line 10, in displayCount
    histo = market_pair
NameError: name 'market_pair' is not defined
Nicolas Cami
  • 458
  • 1
  • 4
  • 13
Olivier R
  • 1
  • 1

1 Answers1

1

In Python, you must use self to access members of an object. So, use self.market_pair to access the attribute:

class CurrenciPair():

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

    def displayCount(self):
        histo = self.market_pair
        print(self.market_pair)

Precision about self

You could also replace self with anything, it's a convention:

class CurrenciPair():

    def __init__(anything, market_pair):
        anything.market_pair = market_pair

    def displayCount(anything):
        print(anything.market_pair)
Nicolas Cami
  • 458
  • 1
  • 4
  • 13