如何将变量从函数传递到类?

2024-09-30 10:39:22 发布

您现在位置:Python中文网/ 问答频道 /正文

如何打印函数外部的路径:

class FirstClas:

    path = ''
    def num(self):
        path = "C:\\Users\\JOHN\\Desktop\\test.txt"
        return path

    print(path)

此方法不打印任何内容

这一结果:

C:\Python\python.exe C:/Users/JOHN/Desktop/test/tt.py

Process finished with exit code 0

Tags: path方法testself路径txtreturndef
3条回答

您的方法永远不会被调用,类变量path在这里是没有意义的。做:

class FirstClas:

    def num(self):
        path = "C:\\Users\\JOHN\\Desktop\\test.txt"
        return path


print(FirstClas().num())  # note that this is outside the class!

我认为您不太了解类的用途,但以下是如何使您所拥有的“工作”(在没有致命错误的意义上):

文件global_variable.py

def init_global_variable():
    """initialize variable"""
    global GLOBALS_DICT
    GLOBALS_DICT = {}


def set_variable(name, value):
    """set variable"""
    try:
        GLOBALS_DICT[name] = value
        return True
    except KeyError:
        return False


def get_variable(name):
    """get variable"""
    try:
        return GLOBALS_DICT[name]
    except KeyError:
        return "Not Found"


init_global_variable()  # ADDED.

文件tt.py

import os
#import lib.global_variable as glv
import global_variable as glv  # Since I don't have your whole package.


class FirstClas:

    def num(self):
        path = "C:\\Users\\JOHN\\Desktop\\test.txt"
        return path

    def imag(self):
        icon_file = os.path.join(
            glv.get_variable("APP_PATH"),
            glv.get_variable("DATA_DIR"),
            "paths",
            "PathExcel",
        )
        return icon_file

class Second:

    # Put statements in a method so they don't run when the class is defined.
    def run(self):
        test = FirstClas()
        print('first: ' + test.num())
        print('second: ' + test.imag())

second = Second()
second.run()

输出:

first: C:\Users\JOHN\Desktop\test.txt
second: Not Found\Not Found\paths\PathExcel

您需要从所创建的类创建一个实例

我建议这样做:

test = FirstClas()
print(test.num())

希望这有帮助

相关问题 更多 >

    热门问题