detroitwilly
detroitwilly

Reputation: 821

Importing Classes from Separate Files

So I'm working on familiarizing myself with object oriented programming by messing around with classes in python. Below is a simple code I [tried] to implement in just 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 start up python, I run the following commands:

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

and then I receive this traceback:

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

I am basing this all off of the official module documentation found here.

I have read quite a bit of documentation on OOP, but I am still very new, so I'm sure there's still something going right over my head. What does that error mean?

Thanks in advance for any help.

Upvotes: 4

Views: 2131

Answers (1)

Praveen Gollakota
Praveen Gollakota

Reputation: 38930

Looks like you're importing the module Test. 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 the unbound method set_name() error. You need call the set_name method on class instance and not directly on the class. Test().set_name("Sean") will work (notice the () after the Test which creates the instance).

The set name method expects an instance of the class Test as a first argument (self). So the method will raise an error if it is not called on an instance. There are ways of calling it directly from a class by explicitly supplying instance as the first parameter.

Upvotes: 6

Related Questions