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.
Looks like you’re importing the module
Test. Do you have a class calledTestinside a module calledTest?If so, you need to import the class directly as
from Test import Testor, if you just want to import the module, you need to refer to your class asTest.Test.EDIT: About the
unbound method set_name()error. You need call theset_namemethod on class instance and not directly on the class.Test().set_name("Sean")will work (notice the()after theTestwhich creates the instance).The set name method expects an instance of the class
Testas 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.