Issue
I'm slowly trying to get my head around classes. I have a few working examples which i kinda understand but can someone please explain to me why this doesn’t work?
class python:
def __init__(self,name):
self.name=name
def changename(self,newname):
self.name=newname
abc=python('python')
print abc.name
abc.changename = 'anaconda'
print abc.name
All I’m trying to do here is change the value of abc.name
at some point later in the code (it doesn’t need to be name if that’s a special word, but I did try name2, etc, same results...)
If I do print abc.changename
then I get the output anaconda but that’s not really what i wanted.
Any help would be much appreciated.
Also...Is it possible to do something like that at a later point in the life cycle of the code?
def newstuff(self, value1, value2):
self.newvalue1 = value1
self.newvalue2 = value2
So that I would have access to 2 new ‘things’ abc.newvalue1
and abc.newvalue2
.
Does that make sense??
Sorry for the ‘things; I’m still trying to grasp which is an attribute, object, method, item, etc...
Solution
Try changing this line:
abc.changename = 'anaconda'
to this:
abc.changename('anaconda')
You defined the method changename
to access your member name
. Then, in the first line you try to access the member directly without using the method.
In the second case, yes it would work:
def newstuff(self, value1, value2):
self.name1 = value1
self.name2 = value2
But you would have to add 1 member to your class, and should then access the method like this:
class python:
def __init__(self, value1, value2):
self.name1 = value1
self.name2 = value2
abc=python('python1', 'python2')
abc.newstuff('snake', 'anaconda')
Answered By - bad_coder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.