Reputation: 101
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
Thank you,
Upvotes: 0
Views: 82
Reputation: 131
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. 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
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.
Upvotes: 1
Reputation: 12416
fncOne
returns tuple (of three elements) in your case.
You can either index like this:
one.fncOne()[1]
... or use more pythonic tuple unpacking:
(_, filetwo, _) = one.fncOne()
Note that you seem to have number of issues in your code, like missing self
in method definition.
Upvotes: 0