0

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

1
  • That's an odd error. Did you import/define Person class properly? Plus you instantiate class by calling it: Person(). Commented Mar 24, 2014 at 17:17

3 Answers 3

2

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()
Sign up to request clarification or add additional context in comments.

8 Comments

I am getting the same error. Do the classes have to be in the same file? Maybe that is what is wrong? They are in the same directory, just different files
@Blossom96 You have to import the Person class before you use it.
Yes if the class is not in the same file, then you need to import the module i.e file, where the class is defined.
After you import the module, you can use the class as module.Class()
Could you please read this docs.python.org/2/tutorial/modules.html about how to import module.
|
2

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

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.