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.v开发者_如何学Pythonal = "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?
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.
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()
精彩评论