dyn added methods dont know self?
moonseeker at my-deja.com
moonseeker at my-deja.com
Wed Feb 2 10:33:33 EST 2000
In article <slrn89g1u2.t0k.scarblac-spamtrap at flits104-37.flits.rug.nl>,
scarblac-rt at pino.selwerd.nl wrote:
> You can just assign to them, self.function = etc.
>
> I think the 'self' is only used when the function you call in an instance
> is part of its class. You can add functions to an instance, but you'd
> have to give the instance manually, I suppose.
>
> class A:
> def __init__(self):
> self.text = "Spam!"
>
> # This function isn't part of the class, yet.
> def foo(self):
> print self.text
>
> # Make an instance
> a = A()
>
> # Make foo an attribute of the *instance*
> a.foo = foo
> # Then it has to be called with the instance
> a.foo(a) # Prints "Spam!"
>
> # However, it can also be added to the *Class*. Then you don't get
> # the problem with the extra argument, but it's added to all instances.
> del a.foo
> A.foo = foo
> a.foo() # Prints "Spam!" as well
>
> So, you call a function in an instance; if it exists in the instance,
> it's just executed. If it doesn't, the interpreter looks in the class,
> and fills in the instance as the first argument (the "self").
>
> Why do you need this, anyway? :)
Hi!
I need this because I have to build an interface to a data string containing
many data fields (output from a database), and I want to say 'Hugo is [2:11],
now I generate a method Hugo() which returns the partial string. I have found
out how to insert a method correct to an instance: new.instancemethod
(function, instance, class) returns a method reference.
Regards,
Mike
PS: I like dynamically generated methods, classes and modules, I use this
heavily in my MUE project.
Sent via Deja.com http://www.deja.com/
Before you buy.
More information about the Python-list
mailing list