rrr at ronadam.com
Sun Oct 2 01:13:01 CEST 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
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: unbound method y() must be called with Xyz instance as first
> (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,
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()
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.
self.q = 2
xyz = Xyz()
print xyz.q # prints 2
More information about the Python-list