[Tutor] Proper uses of classes

Alan Gauld alan.gauld at btinternet.com
Thu Apr 4 00:09:17 CEST 2013


On 03/04/13 20:43, frank ernest wrote:
> Hi guys, it's been a while since I posted and I've learned a lot since
> then. Today I have a question on classes, I can't get mine to work.

Dave has already addressed many issues but there are a few more to consider

> class alist(list):
>
>      def __init__(self, b, a):
>      self = list()

This should be indented but it makes no sense. You are trying to create 
a subclass of list but by assigning self to list you no longer have a 
reference to your class, self now points at an instance of the builtin 
list. self is already a list by the time you get to __init__.

>          self.append(b)

This could work without the list() assignment above.

>          a = a + b

this makes no sense since a and b are arguments passed into the method 
and you don't store the result so it gets thrown away, I assume you intended

self.a = a+b

>      def appendit(self):
>          self.append(a)

Again I assume you meant

self.append(self.a)

And this is odd indeed since it can only ever keep adding the 'a' 
specified during initialization. Normally I'd expect an item to be 
appended to be included in the method call? But then you already have 
that with the inherited append method son maybe this odd behaviour is 
what distinguishes your list from the built in list?

> print(alist(2,4))
>
> []
>
> #It's blank!

Yes because you changed self to be a list and so your alist object had 
no changes made to it.

> c = alist(2,4)
> c.appendit()
> print(c)
> [[...]]
>
> #It's still blank!

No, it now has a list inside, although how that got there I'm not sure!


> If I add this:
>          a = a + b
> the last line of my deffinition I get:

Again you omit self so you are only redefining the local variables, 
except there is no 'a' or 'b' to refer to.


> c = alist(2,4)
>
> c.appendit()
>
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "<stdin>", line 7, in appendit
> UnboundLocalError: local variable 'a' referenced before assignment

Since you didn't pass an a into the method you can't assign it to a.

> If I make a nonlocal I get

What do you mean by making it non local?
What did you do?

> SyntaxError: name 'a' is parameter and nonlocal
>
> I want it to get my list and all the members in it when printing for
> instance. I also would like to without making them global create two
> variables which I can use throughout the whole class as their value will
> not change.

Your problems lie in how you build the class in init...
Get the initialisation right and the append/print methods
will be easy. But see Dave's comments re __str__...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list