Reputation: 31
this is a simplified example of the problem I have. I would like to call var1 in func2, is this possible?
class Plot():
def __init__(self,variable):
self._variable = float(variable)
def func1(self):
var1 = self._variable + 1
print(var1)
def func2(self):
var2 = var1 + 1
print(var2)
the example commands I have tested
h = Plot(3)
h.func1()
h.func2()
and understandably the last command raises issues.
Upvotes: 3
Views: 87
Reputation: 26578
You need to assign a 'self' in front of var1 inside your func1
.
So, do this:
def func1(self):
self.var1 = self._variable + 1
print(var1)
That way in func2, you just do this:
def func2(self):
var2 = self.var1 + 1
print(var2)
An explanation of why exactly this is required.
**Edit: Thanks to @Pynchia for the comments
Let us look at your code to further explain why this is needed:
class Plot():
def __init__(self,variable):
self._variable = float(variable)
def func1(self):
self.var1 = self._variable + 1
print(var1)
def func2(self):
var2 = self.var1 + 1
print(var2)
In short, because it is a very detailed topic, the usage of self allows you to use your variables in the instance namespace, in short, they can be used across your methods, like in the solution I proposed.
So, when you end up creating an instance of your class:
obj = Plot()
Your obj
is now in the instance (object) space/scope, and the way to make "stuff" available to that obj
is by the usage of self in how everything was defined in the above example.
To really understand what is going on, a much longer explanation would be required, and I think the following link really does the description justice, and I strongly recommend reading it:
http://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide
Here is another SO post that will explain this as well:
Upvotes: 6