类错误-缺少1个必需的位置参数

时间:2020-05-29 15:45:56

标签: python python-3.x python-class

我实际上是在学习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'

我不明白为什么。

3 个答案:

答案 0 :(得分:2)

您必须定义一个对象或使该函数静态。
选项1:定义对象:

Array
(
    [0] => 2020-02-01
    [1] => 2020-02-05
)

选项2:静态方法:

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

答案 1 :(得分: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"))

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

答案 2 :(得分:2)

您需要创建一个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)