Reputation: 367
How can use the variable defined by function "plus()" in function "other()"? Assume "plus" function cannot return "v_val".
class klass(object):
def __init__(self,func):
self._func=func
def plus(self,value):
v_val = [1, 2, 3, 4]
funcs=[self._func(v) for v in v_val]
s=0
for i in funcs:
s=s+i
s=s+value
return s
def other(self):
c=0
for i in v_val:
c+=i
return c
I am confused since class cannot have global variables.
Upvotes: 0
Views: 131
Reputation: 3698
Assuming you want to use v_val
, you can make it an instance variable, by prefixing it with self.
:
class klass(object):
def __init__(self,func):
self._func=func
def plus(self,value):
self.v_val = [1, 2, 3, 4]
funcs=[self._func(v) for v in self.v_val]
s=0
for i in funcs:
s=s+i
s=s+value
return s
def other(self):
c=0
for i in self.v_val:
c+=i
return c
More on self
:
Also, you might want to read what PEP8 says about naming conventions when it comes to classes.
Upvotes: 1