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

Python - How to give __init__ values to other classes

我是 Python 的新手,在将 init 值从一个 class 赋给另一个 class 时遇到了一些麻烦。

我读过关于使用 super() 函数可能是一种极其简单的方法,可以将一个 class 的值赋给另一个 class 但是我不太了解知识并且在使用它时遇到了麻烦,我是不确定这是否也是我要找的。

现在我已经编写了一些简单的代码:

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()

我想知道如何从 class 1 发送初始值到 class 2 这样我就可以从 [=27] 打印出那些 init =] 1 里面 class 2?

现在,由于方法 printfunction 不是静态的,您需要一个 class 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)

Python 没有私人 class 成员。这意味着 class 的任何成员(或 class 的任何实例的成员)都可以直接访问,不受外部限制。所以你可以这样做:

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()

或者如果您希望 classTwo 继承自 classOne,您可以这样做:

文件:module_one.py:

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

文件:module_two.py:

import module_one

class ClassTwo(module_one.ClassOne):
    def printFunction(self):
        print(self.test)
        print(self.hello)
        print(self.world)

之所以有效,是因为 classTwoclassOne 继承了 testhelloworld 的值。使用它几乎是一样的,但是 classTwo 不再在其构造函数中使用 classOne 的实例:

>>> import module_two
>>> c2 = module_two.ClassTwo()
>>> c2.printFunction()