Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x TypeError:“输入错误”;用户名';对象在python3中是不可移植的_Python 3.x_Oop - Fatal编程技术网

Python 3.x TypeError:“输入错误”;用户名';对象在python3中是不可移植的

Python 3.x TypeError:“输入错误”;用户名';对象在python3中是不可移植的,python-3.x,oop,Python 3.x,Oop,代码在激活时出错 尝试迭代对象,但没有成功 import os import sys class usernames(object): def __init__(self, filename: str): self.filename = filename self.words = self.file_to_text def file_to_text(self): with open(self.filename, "r") as

代码在激活时出错 尝试迭代对象,但没有成功


import os
import sys

class usernames(object):
    def __init__(self, filename: str):
        self.filename = filename
        self.words = self.file_to_text

    def file_to_text(self):
        with open(self.filename, "r") as f:
            name_list = [line.rstrip() for line in f]

        return name_list


def main():
    user_files = []

    if os.path.isfile(sys.argv[1]):
        filename = os.path.splitext(sys.argv[1])[-1].lower()
        if filename.endswith('.txt'):
            user_files.append(sys.argv[1])

    for files in user_files:
        test_name = usernames(files)
        print(test_name)
    for test in test_name:
        print(test)


if __name__ == '__main__':
    main()
python3 main.py test.txt

cat test.txt

亚历克斯
鲍勃
约翰

但是得到这样的错误

TypeError:“用户名”对象不可编辑

预期输出:

亚历克斯
鲍勃

John

您需要提供一个
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
方法,以使您的对象可移植:

import os
import sys

class usernames(object):
    def __init__(self, filename: str):
        self.filename = filename
        self.words = self.file_to_text()    # <<== needs parens to call method

    def file_to_text(self):
        with open(self.filename, "r") as f:
            name_list = [line.rstrip() for line in f]

        return name_list

    def __iter__(self):
        for word in self.words:
            yield word


def main():
    user_files = ['_test_data.txt']

#     if os.path.isfile(sys.argv[1]):
#         filename = os.path.splitext(sys.argv[1])[-1].lower()
#         if filename.endswith('.txt'):
#             user_files.append(sys.argv[1])

    for files in user_files:
        test_name = usernames(files)
    for test in test_name:
        print(test)


if __name__ == '__main__':
    main()
Alex
bob
John