简体   繁体   English

如何将内容传递给python中的类的实例

[英]How to pass the content into the instance of a class in python

I have a class Book, and this basically only returns the content for now, but i have an external file that i need to read, and then pass the content into that instance, for instance i start declaring the book instance as b1 我有一个Book类,现在基本上只返回内容,但是我有一个需要读取的外部文件,然后将内容传递给该实例,例如,我开始将book实例声明为b1

class Book():
    def __init__(self,poem="empty"):
        self.poem = poem

    def __str__(self):
        return self.poem

def reading(instance, file_content):
    list_of_content = []
    with open(file_content, "r") as f:
        for i in f:
            list_of_content.append(i.split())
    flatten = [item for sublist in list_of_content for item in sublist]
    string = " ".join(flatten) 
    instance = Book(string)
    return instance


b1 = Book() # book has a default value so it wont make any error
reading(b1, "file.txt")
print("File contains:",b1) # prints empty, because reading function has not passed any data i think

The problem is that now it does print always only "empty", how can i pass the data that i read from the file to the instance that is called at reading(), this is for learning purpose. 问题在于,现在它只打印始终为“空”的数据,如何将我从文件读取的数据传递给在read()处调用的实例,这是出于学习目的。

class Book():
    def __init__(self,poem="empty"):
        self.poem = poem

    def __str__(self):
        return self.poem

def reading(self, file_content):
    list_of_content = []
    with open(file_content, "r") as f:
        for i in f:
            list_of_content.append(i.split())
    flatten = [item for sublist in list_of_content for item in sublist]
    string = " ".join(flatten)
    self.poem=string


b1 = Book() 
reading(b1, "file.txt")
print("File contains:",b1)

Output 产量

File contains: I really love christmas Keep the change ya filthy animal Pizza is my fav food Did someone say peanut butter?

For creating instances with some additional functionality for instance often used classmethods https://www.programiz.com/python-programming/methods/built-in/classmethod 为了创建具有某些其他功能的实例,例如常用的类方法https://www.programiz.com/python-programming/methods/built-in/classmethod

Try this one: 试试这个:

class Book():
def __init__(self,poem="empty"):
    self.poem = poem

@classmethod
def load_book(cls, filename):
    list_of_content = []
    with open(filename, "r") as input_file:
        for line in input_file:
            list_of_content.append(line.split())
        flatten = [item for sublist in list_of_content for item in sublist]
        string = " ".join(flatten) 
        book_inst = cls(string)
        return book_inst

def __str__(self):
    return self.poem


book = Book.load_book("input.txt")
print(book)

reading should be a method of the class, but you could also just initialize Book when created: reading应该是该类的一种方法,但是您也可以在创建时初始化Book

class Book():

    def __init__(self,filename):
        list_of_content = []
        with open(filename) as f:
            for line in f:
                list_of_content.append(line.split())
        flatten = [item for sublist in list_of_content for item in sublist]
        string = " ".join(flatten) 
        self.poem = string

    def __str__(self):
        return self.poem

b1 = Book('file.txt')
print("File contains:",b1)

If you still want to create empty books and possibly read different files into the same Book , make read a method: 如果您仍然想创建空的书籍,并可能将不同的文件读入同一Book ,请使用read方法:

class Book():
    def __init__(self,poem='<empty>'):
        self.poem = poem

    def read(self,filename):        
        list_of_content = []
        with open(filename) as f:
            for line in f:
                list_of_content.append(line.split())
        flatten = [item for sublist in list_of_content for item in sublist]
        string = " ".join(flatten) 
        self.poem = string

    def __str__(self):
        return self.poem

b1 = Book()
print("File contains:",b1)
b1.read('file.txt')
print("File now contains:",b1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何调用超出类的方法,并在python django中将类实例传递给它 - how to call a method that is out of the class and pass the class instance to it in python django Python如何将类函数从实例传递给另一个类 - Python how to pass class function from instance to another class 装饰 Python 类方法 - 如何将实例传递给装饰器? - Decorating Python class methods - how do I pass the instance to the decorator? python如何传递Class/Instance中的第一个变量 - How does python pass the first variable in Class/Instance 如何将可调用对象传递给 class 以便它可以访问 Python 中的实例属性? - How to pass a callable to a class so that it can access instance attributes in Python? Python:如何为在另一个类的实例中创建的类的实例传递属性值? - Python: How do I pass a value for an attribute for an instance of a class that is being created within an instance of a different class? Boost-python如何将c ++类实例传递给python类 - Boost-python How to pass a c++ class instance to a python class Python-扩展API客户端类或传递实例 - Python - Extend an API client class or pass instance Tkinter - 如何将实例变量传递给另一个类? - Tkinter - How to pass instance variable to another class? 如何在python中复制类实例? - How to copy a class instance in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM