【问题标题】:How can I use a variable between two methods in a class?如何在类中的两个方法之间使用变量?
【发布时间】:2019-01-11 14:46:42
【问题描述】:

我正在 python 中进行随机排序,但我似乎无法在我的 scramble 方法中使用来自 __init__ 方法的变量 self.fileName。我不知道为什么。

我已经尝试用 fn 完全替换“self”,但是没有定义 self。我试过使用 (self,fn) 但没有任何东西适合 self 参数。

class randomsort:
    def __init__(self,fn):
        self.fileName = fn
        print(self.fileName)

    def scramble(self):
        tempList =[]
        for i in self.fileName:
            ran = random.randrange(0,len(self.fileName))
            tempList.append(self.fileName[ran])
        print("-->",tempList)
        self.fileName = tempList

exlist = [1,2,3,4,5,6,7,8,9,10]
randomsort.scramble(exlist)

预期的输出是列表的未排序版本,但输出是:

AttributeError: 'list' 对象没有属性 'fileName'

【问题讨论】:

    标签: python oop


    【解决方案1】:

    问题在于您没有实例化该类(即您没有向__init__ 方法发送任何内容,只有scramble 正在接收exlist),因此从未定义self.fileName。相反,您应该这样做:

    c = randomsort(exlist) # Create an instance of the object
    c.scramble() # Call method scramble of instance c
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 2011-12-01
      相关资源
      最近更新 更多