0

I'm very new to python and currently practicing OOP. One of the problems I'm facing is how to change an instance variable in python using a method. My code:

class Monster:
   def __init__ (self, name, health):
      self.name = name
      self.health = health
   @classmethod
   def change_name (self, given_name):
      self.name = given_name
mon = Monster("Drake", 100)
print(mon.name)
mon.change_name("Derrick")
print(mon.name)

Output:

#Expected:
Drake 
Derrick
#Actual:
Drake
Drake

Can someone tell me what the problem is and how I can solve it?

0

1 Answer 1

3

It happens because the change_name method is declared as a classmethod

Which means its self parameter is not the object (instance of the class) but the class, in fact you should rename it to cls to make it clear.

Assigning tbe variable via the class creates it in the class' namespace, not in the object's.

But when looked up via the object, python looks for it in the object's namespace and if it cannot be found, it looks for it in the class' (and above in the superclasses' if not found yet)

Since you do not seem to need it , as the name attribute belongs to each monster instance, the solution is to make the method a plain instance one by removing the @classmethod decorator.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.