473,498 Members | 359 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why instancemethod when I can add functions to classes outside class body?

Rim
Hi,

It appears to me the simplest way to add a function to a class outside
of the class declaration is as follows:
class a(object): .... pass
.... def f(self): .... print 'hi'
.... a.f = f
b=a()
b.f()

hi

It works even when the class and the function are in defined in
different modules,
and the call to the method in a third module.

So what problem is the new.instancemethod() trying to solve?

It is ok to point me to a PEP or the like.

Thanks,
- Rim
Jul 18 '05 #1
7 1791
ri*******@yahoo.com (Rim) writes:
So what problem is the new.instancemethod() trying to solve?


It has no side effects on the class it is an instancemethod of.

Regards,
Martin
Jul 18 '05 #2
On 25 Jul 2003 07:18:15 +0200, Martin v. Löwis wrote:
ri*******@yahoo.com (Rim) writes:
So what problem is the new.instancemethod() trying to solve?


It has no side effects on the class it is an instancemethod of.


So what side effects (i.e. what problem) is the new.instancemethod()
trying to solve?

--
\ "I spent a lot of money on wine and women, and like a fool I |
`\ squandered the rest." -- Benny Hill |
_o__) |
http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B
Jul 18 '05 #3
"Ben Finney" <bi****************@and-benfinney-does-too.id.au> wrote:
On 25 Jul 2003 07:18:15 +0200, Martin v. Löwis wrote:
ri*******@yahoo.com (Rim) writes:
So what problem is the new.instancemethod() trying to solve?


It has no side effects on the class it is an instancemethod of.


So what side effects (i.e. what problem) is the new.instancemethod()
trying to solve?


Assigning to the class changes the behaviour of all instances of that
class. new.instancemethod can be used to add a method to an
individual instance.
class A: pass .... a1 = A(); a2 = A()
a1.f = new.instancemethod(lambda self: "hi", a1, A)
a2.f() Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: A instance has no attribute 'f' a1.f()

'hi'
- Anders
Jul 18 '05 #4

"Anders J. Munch" <an******@dancontrol.dk> wrote in message
news:3f***********************@dread11.news.tele.d k...
"Ben Finney" <bi****************@and-benfinney-does-too.id.au> wrote:
On 25 Jul 2003 07:18:15 +0200, Martin v. Löwis wrote:
ri*******@yahoo.com (Rim) writes:
> So what problem is the new.instancemethod() trying to solve?

It has no side effects on the class it is an instancemethod of.


So what side effects (i.e. what problem) is the new.instancemethod()
trying to solve?


Assigning to the class changes the behaviour of all instances of

that class.

Since changing the behavior of all instances is precisely the purpose
of making such an assignment (of function to class as method), that is
a feature, not a problem.
new.instancemethod can be used to add a method to an individual instance. class A: pass ... a1 = A(); a2 = A()
a1.f = new.instancemethod(lambda self: "hi", a1, A)
a2.f() Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: A instance has no attribute 'f' a1.f()

'hi'


So to answer the OP's question, the problem solved is that directly
assigning a function as an instance attribute binds the function as a
function, which means no *automatic* access to the instance and its
other attributes. If such access is needed, the instance must be
passed explicitly, as in
a1.f = lambda self: repr(self)
a1.f(a1)

Instancemethod adds the option of wrapping instance-specific functions
as bound methods getting the instance as an automatic first (self)
paramater, just like with class-wide methods. In the 'hi' example
above, since the self (psuedo)param is is ignored,
a1.f = lambda: 'hi'
would have the same net effect. However,
a1.f = new.instancemethod(lambda self: repr(self), a1, A)
requires the wrapping to avoid having to explicitly pass the instance.

Terry J. Reedy
Jul 18 '05 #5
"Terry Reedy" <tj*****@udel.edu> writes:
So to answer the OP's question, the problem solved is that directly
assigning a function as an instance attribute binds the function as a
function, which means no *automatic* access to the instance and its
other attributes.


To *really* answer the OP's question: API, in general, has no purpose
- it has a function. Whether that function is useful for something
depends on the application. So APIs don't try to solve problems
themselves - it is the developers who solve the problems using the API.

So one may ask "what is the problem that could be solved using
new.instancemethod". These questions often don't have good answers,
and I believe yours isn't much better than that the problem being
solved is

"Create an object of type instancemethod, given the function, the
instance, and the class."

Whether it is useful to create such objects depends on the
application.

Regards,
Martin

Jul 18 '05 #6
Rim
"Terry Reedy" <tj*****@udel.edu> wrote in message
>> class A: pass ...>> a1 = A(); a2 = A()
>> a1.f = new.instancemethod(lambda self: "hi", a1, A)
>> a2.f() Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: A instance has no attribute 'f'
>> a1.f()

'hi'


So to answer the OP's question, the problem solved is that directly
assigning a function as an instance attribute binds the function as a
function, which means no *automatic* access to the instance and its
other attributes. If such access is needed, the instance must be


I don't understand why you say "no automatic access". If you examine
the following, I have access to the attributes defined in the class,
without doing anything special:
class a: .... def __init__(self,name):
.... self.msg = "hi"
.... self.name = name
.... def f(self): .... print "hello"
.... print self.msg
.... print self.name
.... a.f = f
b=a("Joe")
b.f()

hello
hi
Joe

I obviously don't understand what you are trying to explain to me.
So to answer the OP's question, the problem solved is that directly
assigning a function as an instance attribute binds the function as a
function, which means no *automatic* access to the instance and its
other attributes. If such access is needed, the instance must be
passed explicitly, as in
a1.f = lambda self: repr(self)
a1.f(a1)

Instancemethod adds the option of wrapping instance-specific functions
as bound methods getting the instance as an automatic first (self)
paramater, just like with class-wide methods. In the 'hi' example

I think someone should write the official definitions for the following
so we all talk the same language:
- function
- method
- bound method/function
- unbound method/function
- class-wide method/function
- class-not-wide method/function
- etc.
requires the wrapping to avoid having to explicitly pass the instance.


I did not pass the instance and it worked in my example. I'd like to understand
what you are trying to show me.

Thanks,
-Rim
Jul 18 '05 #7

"Rim" <ri*******@yahoo.com> wrote in message
news:6f**************************@posting.google.c om...
"Terry Reedy" <tj*****@udel.edu> wrote in message
So to answer the OP's question, the problem solved is that directly
assigning a function as an instance attribute binds the function as a function, which means no *automatic* access to the instance and its other attributes.
I don't understand why you say "no automatic access".
Re-read the sentence again. The key point is 'assign ... as instance
attribute'.
If you examine
the following, I have access to the attributes defined in the class,
without doing anything special:
class a: ... def __init__(self,name):
... self.msg = "hi"
... self.name = name
... def f(self): ... print "hello"
... print self.msg
... print self.name
... a.f = f
a is the class, not an instance, making the new class attribute f a
method just as if it has been part of the class statement.
b=a("Joe")
b.f()

hello
hi
Joe


Try b.f = f instead and then call b.f() and b.f(b).

Now try b.f = new.instancemethod(f) and then call b.f() and b.f(b).

The results should answer your questions.

Terry J. Reedy
So to answer the OP's question, the problem solved is that directly
assigning a function as an instance attribute binds the function as afunction, which means no *automatic* access to the instance and its
other attributes. If such access is needed, the instance must be
passed explicitly, as in
a1.f = lambda self: repr(self)
a1.f(a1)

Instancemethod adds the option of wrapping instance-specific functionsas bound methods getting the instance as an automatic first (self)
paramater, just like with class-wide methods. In the 'hi' example

Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
3945
by: ‘5ÛHH575-UAZWKVVP-7H2H48V3 | last post by:
(see end of message for example code) When an instance has a dynamically assigned instance method, deepcopy throws a TypeError with the message "TypeError: instancemethod expected at least 2...
1
1844
by: Martin Miller | last post by:
In section "3.27 new -- Creation of runtime internal objects" of the documentation that comes with Python 2.4 it says: > instancemethod(function, instance, class) > > This function will return...
11
8316
by: Peter Salzman | last post by:
I have two files which implement functionality in many of my web pages. Each file uses a function named "parseArguments()" that's critical for each of the two files. I often include both files...
1
1133
by: tshad | last post by:
I actually have 2 questions: 1) I am getting an error "Type 'TempClass1' is not defined" Why? Here is my DLL, where I have 3 classes defined outside of my Web Class: AuthHeader,...
0
817
by: tshad | last post by:
I actually have 2 questions: 1) I am getting an error "Type 'TempClass1' is not defined" Why? Here is my DLL, where I have 3 classes defined outside of my Web Class: AuthHeader,...
2
2129
by: Steven Bethard | last post by:
I'd like to be able to pickle instancemethod objects mainly because I want to be able to delay a call like ``foo(spam, badger)`` by dumping ``foo``, ``spam`` and ``badger`` to disk and loading them...
10
4775
by: John Goche | last post by:
Hello, page 202 of Symbian OS Explained by Jo Stichbury states "All virtual functions, public, protected or private, should be exported" then page 203 states "In the rare cases where a...
15
2152
by: Jess | last post by:
Hello, Sometimes declarations are all what we need when we define/declare classes (or functions?), but sometimes we need definitions. I learned that if we define a class (B) that has an object...
23
2604
by: Chris Gordon-Smith | last post by:
Hello All I have a base class called Action_Request, and a set of classes corresponding to different kinds of Action_Request, each of which inherits from Action_Request. Eg:- class ...
0
6998
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7200
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7375
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4904
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4586
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3090
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1416
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
651
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
287
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.