0

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
Alex Z
  • 347
  • 1
  • 2
  • 13

1 Answers1

1

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.

adder
  • 3,512
  • 1
  • 16
  • 28