1

I'm just starting to learn my way around classes now and I came across something I don't understand. Let's say I have a class...

class Area(object):
    def __init__(self, name, items):
        self.name = name
        self.items = items

Now if I initiate an instance of Area this way:

impala = Area("Impala", ["shotgun", "salt"])

and then call on a variable, say:

print impala.items

it works just fine. However, if I try to initiate it this way:

class impala(Area):
    def __init__(self):
        self.name = "Impala"
        self.items = ["shotgun", "salt"]

and then try to do the same thing it gives me an error: "type object 'impala' has no attribute 'items'"

Could someone please tell me what I'm doing wrong in the second example and why it's happening?

2
  • 2
    class impala(Area) does not create an instance of Area. It defines a subclass of Area called impala. Commented May 10, 2012 at 15:12
  • You never create an instance of your second class. Perhaps I'm misunderstanding your question, but it looks like you are confusing inheritance with instantiation. Commented May 10, 2012 at 15:19

1 Answer 1

4

You are using the same name for your class and variable. impala and impala, I would presume that Python is accessing the class, not the instance.

To avoid this, I recommend following PEP-8 for your variable names, giving classes names in CapWords and local variables lowercase_with_underscores. Naturally, you should also be careful when you name your items not to have two things with the same name in the same namespace.

>>> class Area(object):
...     def __init__(self, name, items):
...         self.name = name
...         self.items = items
... 
>>> class Impala(Area):
...     def __init__(self):
...         self.name = "Impala"
...         self.items = ["shotgun", "salt"]
... 
>>> impala = Impala()
>>> impala.items
['shotgun', 'salt']
Sign up to request clarification or add additional context in comments.

3 Comments

Ok so Impala is a sub-class and not an instance. Got it, thanks for the link!
@Lattyware. Your explanation leaves out that Jen Camara was not creating an instance, which was the key issue.
@StevenRumbalski I did not understand that was what he was trying to do, to be perfectly honest. I won't bother duplicating what has already been said in the comments now though.

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.