I am trying to create a new instance of a class in Python. I tried the solution here: Instances in python
But it didn't work. So, my main class I have
if __name__ == '__main__':
Tim = Person
movement = Person.walk()
Where "Person" is the name of the class that I want to create and instance of. It has methods that I want to use.
I keep getting this error though:
Undefined Variable:Person
I also tried declaring the class instance within the actual metho, not init, but I got the same error.
Any suggestions are welcome. thanks
3 Answers 3
Correction: please use bracket after class if you want to create an instance of that class and use that instance to call the method inside the class.
if __name__ == '__main__':
Tim = Person()
movement = Tim.walk()
OR but less recommended
if __name__ == '__main__':
movement = Person().walk()
8 Comments
import the Person class before you use it.module.Class()You just need to add some parenthesis:
Tim = Person()
This tells python to access the constructor.
The code you provided though tells me you may not have a class Person defined. Your code should have a class Person defined.
class Person:
def walk(self):
print "I'm walking!"
if __name__ == "__main__":
Time = Person
movement = Person.walk()
print movement
or you need a call to import the class Person
from my_other_python_file import Person
if __name__ == "__main__":
Time = Person
movement = Person.walk()
print movement
Comments
You need to have parenthesis to call the constructor.
Tim = Person()
As you have it now, Tim = Person is interpreted as assign Tim the value of the variable Person which hasn't been defined.
Personclass properly? Plus you instantiate class by calling it:Person().