Python-如何将__init__值赋予其他类

问题描述 投票:0回答:2

我是Python的新手,在将init值从一个类提供给另一类时遇到麻烦。

我已经读过有关使用super()函数的方法,这可能是一种将一个类的值提供给另一个类的极其简单的方法,但是我对知识的了解还不够,并且对此感到麻烦,我不确定这是否也是我正在寻找。

到目前为止,我已经将简单的代码编码为:

Class 1:


from classOne import printClass


class classOne:

    def __init__(self):
        self.test = "test"
        self.hello = "hello"
        self.world = "world"

    def main(self,):

        printClass.printFunction(#Send init values#)


test = classOne()
test.main()

# ------------------------------------------------------------------------------- #

Class 2:


class printClass():


    def printFunction(test, hello, world):
        print(test)
        print(hello)
        print(world)


printClass()

而且我想知道如何从类1将初始化值发送到类2,以便可以在类2内从类1中打印出那些init

python class init super
2个回答
1
投票

目前,由于方法printfunction不是静态的,您需要一个类printclass的实例,然后将值作为参数传递

printClass().printFunction(self.test, self.hello, self.world)

如果实例没有特定的参数,您可能还会在printclass中拥有一个静态函数

class printClass:
    @statticmethod
    def printFunction(test, hello, world):
        print(test)
        print(hello)
        print(world)

呼叫将会是

printClass.printFunction(self.test, self.hello, self.world)

0
投票

Python没有私有类成员。这意味着可以直接访问类的任何成员(或该类的任何实例的成员),而不受外部的限制。因此,您可以执行以下操作:

class classOne:
    def __init__(self):
        self.test = "test"
        self.hello = "hello"
        self.world = "world"


class classTwo:
    def __init__(self, class_one):
        self.test = class_one.test
        self.hello = class_one.hello
        self.world = class_one.world
    def printFunction(self):
        print(self.test)
        print(self.hello)
        print(self.world)

然后您可以执行此操作:

>>> class_one = classOne()
>>> class_two = classTwo(class_one)
>>> class_two.printFunction()
© www.soinside.com 2019 - 2024. All rights reserved.