Shaokan
Shaokan

Reputation: 7684

why does this code do not work? (python)

class MyClass:

     def __init__(self):
         pass

     val = ""

     def getval(self):
         # code to get val 
         # ... and at the end:
         self.val = "bla bla"

     self.getval()
     print val

Now at this point it says that the name self is not found. If I try only getval() (without the self prefix) then it says that no getval method takes 0 arguments. Please anyone can explain me why does this code do not work?

Upvotes: 0

Views: 188

Answers (2)

Jochen Ritzel
Jochen Ritzel

Reputation: 107608

Here is a example that makes slightly more sense:

class MyClass:
     def __init__(self):
         pass

     # this is a class variable
     val = ""

     def getval(self):
         # code to get val 
         # ... and at the end:
         self.val = "bla bla"
         return self.val

# make a instance of the class
x = MyClass()
print x.getval()

# MyClass.val is a different class variable
print MyClass.val

Read the Python tutorial.

Upvotes: 6

mdm
mdm

Reputation: 12630

You haven't created an instance of the object.

class MyClass:
    def __init__(self):
        pass

    val = ""

    def getval(self):
        # code to get val 
        # ... and at the end:
        self.val = "bla bla"

     self.getval()
     print val

o = MyClass()
print o.getval()

Upvotes: 1

Related Questions