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
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
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()
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.