Class Help

Ron Adam rrr at ronadam.com
Sat Oct 1 19:13:01 EDT 2005


Ivan Shevanski wrote:
> To continue with my previous problems, now I'm trying out classes.  But 
> I have a problem (which I bet is easily solveable) that I really don't 
> get.  The numerous tutorials I've looked at just confsed me.For intance:
> 
>>>> class Xyz:
> 
> ...     def y(self):
> ...             q = 2
> ...
> 
>>>> Xyz.y()
> 
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
> TypeError: unbound method y() must be called with Xyz instance as first 
> argument
> (got nothing instead)
> 
> 
> So. . .What do I have to do? I know this is an extremley noob question 
> but I think maybe if a person explained it to me I would finally get it =/
> 
> 
> thanks in advance,
> 
> -Ivan

Generally you don't use class's directly.  Think if them as templates 
for objects.  Then you can use that class (template) to create many objects.

To create an object just call the class and assign the result to a name.

xyz = Xyz()
xyz.y()


Also,

In your example 'q' is assigned the value 2, but as soon as the method 
'y' exits, it is lost.  To keep it around you want to assign it to self.y.

class Xyz(object):   #  create an class to create an object instance.
    def y(self)
       self.q = 2

xyz = Xyz()
xyz.y()
print xyz.q          #  prints 2



Cheers,
Ron














More information about the Python-list mailing list