简体   繁体   English

如何替换python类中的变量?

[英]How do I replace variables in python class?

I was instructed to define a class which takes 3 variables: (which looks something like this) 我被要求定义一个包含3个变量的类:(看起来像这样)

class random(object):
    def __init__(self,a,b,c):
        self.a=a
        self.b=b
        self.c=c
        self.result= #calculations with a,b and c.
    def __str__(self):
        #functions so that self.result prints correctly

However, I also have to write another function in the above class: 但是,我还必须在上述类中编写另一个函数:

    def read(#takes whatever parameter I need)
         #functions which I dont know how to write

This function should allow me to read from another file (lets call it file.txt"), and replace the self.a, self.b and self.c with information from that file, if you know what I mean? like for example: 此功能应允许我读取另一个文件(将其称为file.txt“),并用该文件中的信息替换self.a,self.b和self.c(如果您知道我的意思?例如,例如:

itemA=random(1,2,3) 

and file.txt contains three lines: 和file.txt包含三行:

6
7
8

running the following: 运行以下命令:

itemA.read()

is suppose to replace the 1,2,3 in the parameter as 6,7,8, so that 假设将参数中的1,2,3替换为6,7,8,这样

itemA=random(6,7,8)

How can I achieve that? 我该如何实现? I already wrote the part that reads and reproduce random(6,7,8),with: 我已经写了读取和复制random(6,7,8)的部分,内容如下:

fileHandle=open('file.txt', 'r')
fileHandle.readlines()
#some codes that turn string into integer/floats
fileHandle.close()
random(#put integers in)

however I am not able to update itemA from random(1,2,3) to random(6,7,8) without writing manually: 但是,如果不手动编写,就无法将itemA从random(1,2,3)更新为random(6,7,8):

itemA=itemA.read() #in python shell

btw itemA is just an example name, it can be named anything so I cant actually use itemA in my calculations... 顺便说一句itemA只是一个示例名称,它可以命名为任何名称,因此我不能在计算中实际使用itemA ...

Inside a method on your class, you can manipulate attributes by setting them on self , just like you did in the __init__ method. 在类的方法内部,您可以通过将属性设置为self来操纵属性,就像在__init__方法中所做的那样。

All you need to do then is set those attributes after reading. 然后,您需要做的就是在阅读后设置这些属性。 You probably want your read() method to take a filename too: 您可能还希望read()方法也采用文件名:

def read(self, filename):
    with open(filename) as fh:
        self.a = int(fh.readline())
        self.b = int(fh.readline())
        self.c = int(fh.readline())
        self.result = # same calculation

So when you call itemA.read() it'll alter the attributes in place ; 因此,当您调用itemA.read()它将在适当位置更改属性; there is no need to return anything here. 这里不需要返回任何东西。

You could reuse the __init__ method to set those attributes, and avoid having to duplicatoe the calculation for the self.result attribute: 您可以重用 __init__方法来设置那些属性,并避免重复对self.result属性进行计算:

class random(object):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self.result = #calculations with a,b and c.

    def read(self, filename):
        with open(filename) as fh:
            a = int(fh.readline())
            b = int(fh.readline())
            c = int(fh.readline())
            self.__init__(a, b, c)  # set the attributes plus result

or you could share a separate method between __init__ and read() : 或者您可以在__init__read()之间共享一个单独的方法:

class random(object):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self._calculate_result()

    def _calculate_result(self)
        self.result = #calculations with self.a, self.b and self.c.

    def read(self, filename):
        with open(filename) as fh:
            self.a = int(fh.readline())
            self.b = int(fh.readline())
            self.c = int(fh.readline())
            self._calculate_result()  # set the result

It would work something like this: 它会像这样工作:

itemA = random(1, 2, 3)
itemA.read('file.txt')
# now itemA.a is set to 4, itemA.b is set to 5 and item.c is set to 6

It could be that you wanted to produce an instance of the class random either by providing a , b and c directly , or by reading from a file. 可能是您想通过直接提供abc 从文件中读取来产生random类的实例。 This is a little more advanced, but that means you are providing two different factory methods , two different ways to produce instances of random . 这稍微先进一点,但这意味着您将提供两种不同的工厂方法 ,两种不同的方法来产生random实例。 I tend to use class methods to implement extra factory methods: 我倾向于使用类方法来实现额外的工厂方法:

class random(object):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self.result = #calculations with a,b and c.

    @classmethod
    def from_file(self, filename):
        with open(filename) as fh:
            a = int(fh.readline())
            b = int(fh.readline())
            c = int(fh.readline())
            return cls(a, b, c)  # create a new instance of this class

I renamed the read method to from_file() to document better that this is a factory method. 我将read方法重命名为from_file()以更好地说明这是一种工厂方法。 You'd use it like this: 您可以这样使用它:

itemA = random(1, 2, 3)
itemB = random.from_file('file.txt')

This creates two separate instances, one with values provided directly, the other by reading from a file. 这将创建两个单独的实例,一个实例直接提供值,另一个实例通过读取文件来实现。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM