简体   繁体   English

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

[英]Python: How do I call a specific variable from a function inside the class?

I have Basic question How do I call a specific variable from a function inside the class? 我有一个基本问题:如何从类中的函数调用特定变量? let say I have this 可以说我有这个

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

        return fileOne ,filetwo,filethree

fncOne() // Will call all of them together

But I want to call only one of them to print it fncOne().filetwo 但是我只想调用其中一个来打印它fncOne()。filetwo

Thank you, 谢谢,

The way your code is structured now, I don't think anything will happen at all. 现在代码的结构方式,我认为什么都不会发生。 First, you made a class with a method inside of it, but the method has no "self" argument so you will get an error. 首先,您创建了一个内部带有方法的类,但是该方法没有“ self”自变量,因此您将得到错误。 Second, the "return" is not inside of the method. 其次,“返回”不在方法内部。

Even if you fix where the return is, as soon as you instantiate the "One" object, an error will be thrown: 即使您修复了返回的位置,一旦实例化“一个”对象,也会引发错误:

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

a = One()
a.fncOne()

This will get you: TypeError: fncOne() takes 0 positional arguments but 1 was given 这将为您提供:TypeError:fncOne()接受0个位置参数,但给出了1个

However, if you take the method out of the class definition, the above comments are fine: 但是,如果您从类定义中删除该方法,则上面的注释会很好:

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

fncOne()[1]

That will return 'two' as you desire. 这将返回您想要的“二”。

However, you want to keep the class so maybe what you need to do instead is: 但是,您想保留该类,所以也许您需要做的是:

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

myObject = One()
myObject.fileTwo

That will return 'two' because 'fileTwo' is now an attribute of the class One. 这将返回“ two”,因为“ fileTwo”现在是类One的属性。

fncOne returns tuple (of three elements) in your case. 在您的情况下, fncOne返回元组(包含三个元素)。

You can either index like this: 您可以这样索引:

one.fncOne()[1]

... or use more pythonic tuple unpacking: ...或使用更多pythonic元组解压缩:

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

Note that you seem to have number of issues in your code, like missing self in method definition. 请注意,您的代码中似乎有很多问题,例如方法定义中缺少self

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM