-4

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

我不明白为什么。

4

3 回答 3

2

您必须定义一个对象或使函数成为静态的。
选项 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"))
于 2020-05-29T15:51:39.967 回答
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"))

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

于 2020-05-29T15:51:53.117 回答
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)
于 2020-05-29T15:55:28.133 回答