Python:如何从类内的函数调用特定变量?

2024-09-29 21:58:44 发布

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

我有个基本问题 如何从类内的函数调用特定变量? 假设我有这个

class One():
    def fncOne():
        fileOne = "one"
        filetwo= "two"
        filethree= "three"

        return fileOne ,filetwo,filethree

fncOne() // Will call all of them together

但我只想调用其中一个来打印它fncOne().filetwo

谢谢你


Tags: returndefallcallonewillclassthree
2条回答

fncOne返回大小写中的元组(三个元素)。你知道吗

您可以这样索引:

one.fncOne()[1]

。。。或者使用更多pythonic元组解包:

(_, filetwo, _) = one.fncOne()

请注意,代码中似乎存在许多问题,例如方法定义中缺少self。你知道吗

你现在的代码结构,我不认为会发生任何事情。首先,您创建了一个类,其中包含一个方法,但是该方法没有“self”参数,因此您将得到一个错误。第二,“返回”不是方法的内部。你知道吗

即使修复了返回的位置,只要实例化“One”对象,就会抛出一个错误:

class One():
    def fncOne():
        fileOne = "one"
        filetwo = "two"
        filethree = "three"
        return fileOne, filetwo, filethree

a = One()
a.fncOne()

这将使您: TypeError:fncOne()接受0个位置参数,但给出了1个

但是,如果将该方法从类定义中移除,则上面的注释就可以了:

def fncOne():
    fileOne = "one"
    filetwo = "two"
    filethree = "three"
    return fileOne, filetwo, filethree

fncOne()[1]

这将返回“2”作为你的愿望。你知道吗

但是,你想继续上课,所以也许你需要做的是:

class One(object):
    def __init__(self):
        self.fileOne = "one"
        self.fileTwo = "two"
        self.fileThree = "three"

myObject = One()
myObject.fileTwo

它将返回'two',因为'fileTwo'现在是类1的属性。你知道吗

相关问题 更多 >

    热门问题