newbie class question

Justin Sheehy dworkin at ccs.neu.edu
Sun Aug 13 20:31:49 EDT 2000


[Sorry for my first followup to this.  My fingers were too quick for me.]

"Ron Johnson, Jr." <ronjohn at gs.verio.net> writes:

> What am I doing wrong when trying tp access the method f() ?

You are making two mistakes here.

> >>> class MyClass:
> ...     i = 12345
> ...     def f(x):
> ...             return 'hello world'

>From the way that you call it later, I suspect that you would be
better off defining the method 'f' as follows:

    def f(self, x):
        return 'hello world'

Note the explicit 'self' parameter.

> >>> x = MyClass

Here, you are simply making 'x' an equivalent name to 'MyClass'.  To
instantiate a member of the class, do it like this:

>>> x = MyClass()

Note the parentheses.

> >>> print x.f(1)
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> TypeError: unbound method must be called with class instance 1st argument

With those two changes, you should be able to do this:

>>> print x.f(1) 
hello world
>>> 

-Justin

 





More information about the Python-list mailing list