get a self data in a method call

Troy Melhase troy at gci.net
Sun Dec 22 19:55:43 EST 2002


Consider this approach, but note that there are others:

Python 2.2 (#1, Mar 30 2002, 22:23:59)
[GCC 2.95.3 [FreeBSD] 20010315 (release)] on freebsd4
Type "help", "copyright", "credits" or "license" for more information.
 >>> class MyClass:
...     def __init__(self):
...             self.data = 123
...     def func(self, data=None):
...             if data is None:
...                     data = self.data
...             print self, data
...
 >>> o = MyClass()
 >>> o.func()
<__main__.MyClass instance at 0x8117ccc> 123
 >>> o.func(1)
<__main__.MyClass instance at 0x8117ccc> 1
 >>>

However, you may want to consider changing the code that calls 'func' to 
include all arguments explicitly.  Using keyword arguments can result in 
behavior that is complicated and difficult to understand.

Good luck.

troy



polux wrote:

> I've a class
>
> class MyClass:
>
>     def __init__(self):
>         self.data = 123
>
>
> now, I want to define a method, which would be like that if it were
> possible :
>
>     def func(self, data = self.data )
>
> but it doesn't work because python does't know yet what "self" is
>
>
>
> please help
>
>
> ps : excuse my poor english
>




More information about the Python-list mailing list