[英]Python: How do I call a specific variable from a function inside the class?
我有一个基本问题:如何从类中的函数调用特定变量? 可以说我有这个
class One():
def fncOne():
fileOne = "one"
filetwo= "two"
filethree= "three"
return fileOne ,filetwo,filethree
fncOne() // Will call all of them together
但是我只想调用其中一个来打印它fncOne()。filetwo
谢谢,
现在代码的结构方式,我认为什么都不会发生。 首先,您创建了一个内部带有方法的类,但是该方法没有“ self”自变量,因此您将得到错误。 其次,“返回”不在方法内部。
即使您修复了返回的位置,一旦实例化“一个”对象,也会引发错误:
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]
这将返回您想要的“二”。
但是,您想保留该类,所以也许您需要做的是:
class One(object):
def __init__(self):
self.fileOne = "one"
self.fileTwo = "two"
self.fileThree = "three"
myObject = One()
myObject.fileTwo
这将返回“ two”,因为“ fileTwo”现在是类One的属性。
在您的情况下, fncOne
返回元组(包含三个元素)。
您可以这样索引:
one.fncOne()[1]
...或使用更多pythonic元组解压缩:
(_, filetwo, _) = one.fncOne()
请注意,您的代码中似乎有很多问题,例如方法定义中缺少self
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.