【问题标题】:How to get the specific object inside the function using Python?如何使用 Python 获取函数内部的特定对象?
【发布时间】:2021-03-08 08:13:33
【问题描述】:

我在下面有一个 python 代码。我想获取函数内部对象之一的值。例如,我想在另一个进程函数中获取此 tmpdict["CpuType"] = cpu.Name 的值。 如何使用此功能获得它。谢谢

import wmi
c = wmi.WMI()

def printCPU():
    tmpdict = {}
    tmpdict["CpuCores"] = 0
    for cpu in c.Win32_Processor():
        tmpdict["cpuid"] = cpu.ProcessorId.strip()
        tmpdict["CpuType"] = cpu.Name
        tmpdict['systemName'] = cpu.SystemName
        try:
            tmpdict["CpuCores"] = cpu.NumberOfCores
        except:
            tmpdict["CpuCores"] += 1
        tmpdict["CpuClock"] = cpu.MaxClockSpeed
        tmpdict['DataWidth'] = cpu.DataWidth
    print(tmpdict)
    return tmpdict
printCPU()

【问题讨论】:

  • 你不回tmpdict吗?它包含密钥"CpuType",因此您可以将其传递给另一个函数。
  • 不,我不知道。我只需要tmpdict["CpuType"] = cpu.Name 的值就可以在另一个函数@ccarstens 中处理它
  • 那么最后一行会发生什么?
  • 如果我在最后一行添加printCPU() ini,那么它将打印所有cpuid, CpuType, systemName 的值。但我的期望是我需要单独阅读该值。 @ccarstens

标签: python function object


【解决方案1】:

您在tmpdict 中获得了CpuType 值:


def printCPU():
    ...

def otherFunction(cpuType):
    # do something with cpuType
    ...

cpuValues = printCPU()

otherFunction(vpuValues['CpuType'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    相关资源
    最近更新 更多