模块导入类函数

时间:2018-04-30 15:15:56

标签: python string class import arguments

你好,我有一个愚蠢的pb困扰我,我不明白为什么str参数没有考虑到:

这是 tst.py

class CurrenciPair():

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

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

课外:

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

以下是导入上一个文件的 test.py

import tst as tt

market = 'TEST'
tt.reco(market)

结果如下:

>>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

1 个答案:

答案 0 :(得分:1)

在Python中,您必须使用self来访问对象的成员。因此,使用self.market_pair访问属性:

class CurrenciPair():

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

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

关于自我的精确度

你也可以用任何东西取代self,这是一个惯例:

class CurrenciPair():

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

    def displayCount(anything):
        print(anything.market_pair)