Reputation: 1
I've been learning Python for one week now and I've been trying to create a text based game. Everything so far is good, I've been able to write lots of useful code but I just get this same problem and I don't know why.
Whenever it's time to define the name and the color of the character (its a frog). I thought that using a class would be the most appropiate thing, the problem is that when I try to call the member to change its content I get the next problem: Class Frog has no 'name' member, it also happens with color
The problem is that I defined it in the class which contains the player atributes.
Here is the piece of code that is giving me problems.
class Frog:
def __init__(self, name, color):
self.name = str
self.color = str
def changeAtributes():
print("change name")
option = input("--> ")
Frog.name == option
print("\nchange color")
option = input("-->")
Frog.color == option
changeAtributes()
Upvotes: -1
Views: 488
Reputation: 71
Your changeAtributes
function should be a method of the class Frog
, not a regular function.
A method is like a normal function, but it's first argument is self
.
class Frog:
def __init__(self, name, color):
self.name = name
self.color = color
def changeAtributes(self, name, color):
self.name = name
self.color = color
def __str__(self):
"""return a string representing the class instance"""
return f'name: {self.name}, color: {self.color}'
frog = Frog("jumpy", "red")
print(frog)
print("change name")
name = input("--> ")
print("\nchange color")
color = input("-->")
frog.changeAtributes(name, color)
print(frog)
$ python frog.py
name: jumpy, color: red
change name
--> sleepy
change color
-->blue
name: sleepy, color: blue
Upvotes: 0
Reputation: 370
You didn't instantiate your class. You have to first assign the parameters of name
and color
in the dunder __init__
which is in the Frog Class. After that you will be able to modify the values in the changeAttributes
function. And to change the values in the Frog Class using the function, you have to pass the instantiated class as an argument to teh function.
class Frog:
def __init__(self, name, color):
self.name = str
self.color = str
def changeAtributes(frogObject): # Pass frogObject as an argument.
print("change name")
option = input("--> ")
Frog.name == option
print("\nchange color")
option = input("-->")
Frog.color == option
frogObject = Frog("Molly", "Green")
changeAtributes(frogObject)
Upvotes: 0
Reputation: 2687
You're trying to change attributes of the class itself, not instantiations of that class - i.e., you have to first define a frog with something like frog = Frog(name='nick', color='green'
and then call your changeAttributes
function like so:
def changeAtributes(frog):
print("change name")
option = input("--> ")
frog.name = option
print("\nchange color")
option = input("-->")
frog.color = option
frog = Frog(name='nick', color='green')
changeAtributes(frog)
Upvotes: 1