Import classes from individual files

So, I am working to familiarize myself with object-oriented programming by teaming with classes in python. Below is a simple code that I [tried] to implement only in the interpreter.

class Test(object): def set_name(self, _name): name = _name def set_age(self, _age): age = _age def set_weight(self, _weight): weight = _weight def set_height(self, _height): height = _height 

When I run python, I run the following commands:

 >>>import Test >>>Test.set_name("Sean") 

and then I get this trace:

 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'set_name' 

I base all of this on the official module documentation found here .

I read quite a lot of OOP documentation, but I'm still very new to it, so I'm sure something is still happening right above my head. What does this error mean?

Thanks in advance for your help.

+4
source share
1 answer

It looks like you are importing a Test module. Do you have a class called Test inside a module called Test ?

If so, you need to import the class directly as from Test import Test or if you just want to import the module, you need to refer to your class as Test.Test .

EDIT: About unbound method set_name() error. You need to call the set_name method on the class instance, and not directly on the class. Test().set_name("Sean") will work (note the () after Test , which creates the instance).

The set name method expects an instance of the Test class as the first argument ( self ). Thus, the method will throw an error if it is not called per instance. There are ways to call it directly from the class by explicitly providing the instance as the first parameter.

+5
source

Source: https://habr.com/ru/post/1397473/


All Articles