类中的错误-缺少1个必需的位置参数[关闭]

Posted

技术标签:

【中文标题】类中的错误-缺少1个必需的位置参数[关闭]【英文标题】:Error in classes - missing 1 required positional argument [closed] 【发布时间】:2020-09-17 05:58:06 【问题描述】:

我实际上正在学习python3,但无法弄清楚为什么会这样

class Load():
    def __init__(self):
        print("Starting Now")
        self.player = []
    def player_Stats(self,filename):
        with open(filename) as my_names:
            names = my_names.readlines()
            for one in names:
                one.replace("\n","")
                self.player.append(one.split[":"][0])
                print(player)


print(Load.player_Stats("players.txt"))

它给了我一个错误

Traceback (most recent call last):
  File "test.py", line 56, in <module>
    print(Load.player_Stats("players.txt"))
TypeError: player_Stats() missing 1 required positional argument: 'filename'

我不明白为什么。

【问题讨论】:

您是否打算将该方法作为静态/类方法?你有它作为实例方法,但你在类本身上调用它。 这能回答你的问题吗? TypeError: Missing one required positional argument 【参考方案1】:

您必须定义一个对象或将函数设为静态。选项 1:定义对象:

class Load():
    def __init__(self):
        print("Starting Now")
        self.player = []
    def player_Stats(self,filename):
        with open(filename) as my_names:
            names = my_names.readlines()
            for one in names:
                one.replace("\n","")
                self.player.append(one.split[":"][0])
                print(player)

load = Load()
print(load.player_Stats("players.txt"))

选项 2:静态方法:

class Load():
    def __init__(self):
        print("Starting Now")
        self.player = []
    @staticmethod
    def player_Stats(filename):
        with open(filename) as my_names:
            names = my_names.readlines()
            for one in names:
                one.replace("\n","")
                self.player.append(one.split[":"][0])
                print(player)


print(Load.player_Stats("players.txt"))

【讨论】:

【参考方案2】:

试试这个:

lass Load():
    def __init__(self):
        print("Starting Now")
        self.player = []
    def player_Stats(self,filename):
        with open(filename) as my_names:
            names = my_names.readlines()
            for one in names:
                one.replace("\n","")
                self.player.append(one.split[":"][0])
                print(player)

load = Load()

print(load.player_Stats("players.txt"))

问题是当你有一个类时,你必须创建它的一个实例。然后你就可以调用它的方法了。

【讨论】:

【参考方案3】:

您需要创建Load 的新实例才能使用player_Stats 方法:

load = Load()
print(load.player_Stats("players.txt"))

此外,您的代码中还有一些其他错误:

self.player.append(one.split[":"][0])
# should be
self.player.append(one.split(":")[0])

print(player)
# should be
print(self.player)

【讨论】:

以上是关于类中的错误-缺少1个必需的位置参数[关闭]的主要内容,如果未能解决你的问题,请参考以下文章

类型错误:预测()缺少 1 个必需的位置参数:sklearn KMeans 中的“X”

TypeError:fit_resample()缺少1个必需的位置参数:'y'[关闭]

__init__() 缺少 1 个必需的位置参数:'self' [关闭]

“fit() 缺少 1 个必需的位置参数:'y'”错误

类型错误:parse() 缺少 1 个必需的位置参数:'stream'

类型错误:initialize() 缺少 1 个必需的位置参数:'url'