'A question about variables in classes Python 3
so i notice that if i run it like this it works. Gets my name and prints the talk method with the name inside the string.
but if i take out the input and put the name inside the Person class then the talk method doesnt work anymore. It says that the name variable is not defined. So why is the
#self.name = name different from the #f"my name is{name}" variable?
class Person:
def __init__(self, name):
self.name = name
def talk(self):
print(f"my name is {name}")
name = input("enter name: ")
talk_person = Person(name)
talk_person.talk()
Solution 1:[1]
What is happening here is that you are "leaking" the name variable from your global context into the talk function.
You need to update the talk function to this:
def talk(self):
print(f"my name is {self.name}")
This way, you specify the name variable from the Person instance.
A good way to demonstrate this is like so:
name = input("enter name: ")
talk_person = Person(name)
name = "This is a mistake, I did not mean to print this"
talk_person.talk()
With your current talk function, the invalid name line will print, while with the fixed function the correct name that the user entered will be outputed.
An other example of this can be seen by changing the name of the global name variable like so:
global_name = input("enter name: ")
talk_person = Person(global_name)
talk_person.talk()
When the talk function is called you script will exit with a NameError exception stating that you do not have a name variable defined.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nadav Barghil |
