Problems instantiating objects in python

Asked

Viewed 58 times

1

I’m new to programming, but I just came from Java and I’m migrating to Python.. To start I created a simple Person class with 3 attributes and tried to instantiate it to see the syntax, but I just can’t understand why it doesn’t work...

The Class

class Person:
    def __init__(self, Name, Age, Height):
        self.name = Name
        self.age = Age
        self.height = Height

The file "Main"

import Person

if __name__ == "__main__":
    person = Person("Mateus", 18, 1.8)
    print(person.name)

And makes the mistake:

File "c:\Users\Lenovo\Desktop\python\main.py", line 4, in <module>
    person = Person("Mateus", 18, 1.8)
TypeError: 'module' object is not callable

Sorry for being stupid and thank you so much for your help.

  • Typeerror: 'module' Object is not callable

  • Vlw kkk am new aq too

  • What do you call the file containing the class? It’s a module, and at the top of the other file you need to use from modulo import Person instead of what you did.

1 answer

2


I don’t know the structure of your project, but in order to be able to invoke a class, you must be running your code on a python path.

The definition of a python-path is to have a file __init__.py in your python project folder structure.

Follow an example of the folder structure:

.
├── __init__.py
├── person.py
└── main.py

Follows how the contents of the files are:

person py.

class Person:
    def __init__(self, Name, Age, Height):
        self.name = Name
        self.age = Age
        self.height = Height

main py.

from person import Person

if __name__ == "__main__":
    person = Person("Mateus", 18, 1.8)
    print(person.name)

then to invoke this function just execute the following command:

python main.py
#Mateus

After executing this command your code will be executed successfully.

  • It worked perfectly! Thanks mt

Browser other questions tagged

You are not signed in. Login or sign up in order to post.