473,513 Members | 2,425 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

methods and functions, instances and classes

When I create an instance of a class,
are the class's functions *copied* to create the methods?
Or are method calls actually calls of the class's functions?

I am sure this is both obvious and FAQ,
but I did not find a clear answer
(e.g. here
http://docs.python.org/tut/node11.ht...00000000000000 ,
a lot turns on the meaning of 'equivalent'.)

Thank you,
Alan Isaac
Sep 4 '06 #1
5 1317
David Isaac wrote:
When I create an instance of a class,
are the class's functions *copied* to create the methods?
Or are method calls actually calls of the class's functions?
On the class functions. You can make every instance have it's own methods,
though - but only explicitly.

Diez

Sep 4 '06 #2
When I create an instance of a class,
are the class's functions *copied* to create the methods?
Or are method calls actually calls of the class's functions?

I am sure this is both obvious and FAQ,
but I did not find a clear answer
The best way to find out is to try it:

#######################################
class Foo(object):
def hello(self):
return "Foo::hello"

f1 = Foo()

print f1.hello()
Foo.hello = lambda self: "new hello!"
print f1.hello()

#######################################

From what I see of this evidence, "method calls [are] actually
calls of the class's functions", not copied.

-tkc


Sep 4 '06 #3
Alan Isaac wrote:
When I create an instance of a class,
are the class's functions *copied* to create the methods?
Or are method calls actually calls of the class's functions?

"Diez B. Roggisch" <de***@nospam.web.dewrote in message
news:4m************@uni-berlin.de...
On the class functions. You can make every instance have it's own methods,
though - but only explicitly.

Could you please elaborate on that last sentence?
Thanks,
Alan Isaac
Sep 4 '06 #4
David Isaac wrote:
When I create an instance of a class,
are the class's functions *copied* to create the methods?
No, unless you explicitely do it.
Or are method calls actually calls of the class's functions?
Depends on how the method was associated to the instance (you can set
methods on a per-instance property), but in the general case (functions
defined in the class body), yes.
I am sure this is both obvious
I once had the same question when I was learning computers and programming.
and FAQ,
Not AFAIK.
but I did not find a clear answer
(e.g. here
http://docs.python.org/tut/node11.ht...00000000000000 ,
a lot turns on the meaning of 'equivalent'.)

"""
If the name denotes a valid class attribute that
is a function object, a method object is created by packing (pointers
to) the instance object and the function object just found together in
an abstract object: this is the method object. When the method object is
called with an argument list, it is unpacked again, a new argument list
is constructed from the instance object and the original argument list,
and the function object is called with this new argument list.
"""

IOW, a method object is a callable object keeping references to both the
instance and the function (note the "(pointers to) ... the function
object").

You could represent yourself the method as something like:

class Method(object):
def __init__(self, im_func, im_self):
self.im_self = obj
self.im_func = func

def __call__(self, *args, **kw):
return self.im_func(self.im_self, *args, **kw)

Now suppose that the 'function' type definition (yes, Python functions
are objects) looks a bit like this:

class function(object):
. . .
def __get__(self, obj):
return Method(self, obj)
And that looking up an attribute on an instance looks like this (dumbed
down of course):

def __getattribute__(self, name):
if name in self.__dict__:
return self.__dict__[name]
elif hasattr(self.__class__, name)
attrib = getattr(self.__class__, name)
if hasattr(attrib, '__get__'):
return attrib.__get__(self)
else:
return attrib
else:
raise AttributeError("object %s has no attribute %s" % (self, name)
Then for :

class Foo(object):
def bar(self, val):
return "%s %s" % (self, val)

foo = Foo()

Looking up 'bar' on 'foo':
bar = foo.bar

would resolve, thru __getattribute__ etc, to:
bar = Method(Foo.bar, foo)

Which, if then called, would resolve to
Foo.bar(foo, 42)

NB : reading the doc about new-style classes and the descriptor protocol
may help:
http://www.python.org/download/relea....3/descrintro/
http://users.rcn.com/python/download/Descriptor.htm

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Sep 4 '06 #5
Alan Isaac wrote:
are method calls actually calls of the class's functions?
"Bruno Desthuilliers" <on***@xiludom.growrote in message
news:44*********************@news.free.fr...
Depends on how the method was associated to the instance (you can set
methods on a per-instance property), but in the general case (functions
defined in the class body), yes.

[much useful stuff snipped]

Thanks!
Alan
Sep 4 '06 #6

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

Similar topics

13
10673
by: Axehelm | last post by:
Okay, I'm in a debate over whether or not static methods are a good idea in a general domain class. I'm personally not a fan of static methods but we seem to be using them to load an object. ...
99
5819
by: David MacQuigg | last post by:
I'm not getting any feedback on the most important benefit in my proposed "Ideas for Python 3" thread - the unification of methods and functions. Perhaps it was buried among too many other less...
0
2329
by: Anthony Baxter | last post by:
To go along with the 2.4a3 release, here's an updated version of the decorator PEP. It describes the state of decorators as they are in 2.4a3. PEP: 318 Title: Decorators for Functions and...
51
6882
by: Noam Raphael | last post by:
Hello, I thought about a new Python feature. Please tell me what you think about it. Say you want to write a base class with some unimplemented methods, that subclasses must implement (or...
8
2928
by: Kevin Little | last post by:
#!/usr/bin/env python ''' I want to dynamically add or replace bound methods in a class. I want the modifications to be immediately effective across all instances, whether created before or...
11
2270
by: Steven D'Aprano | last post by:
Suppose I create a class with some methods: py> class C: .... def spam(self, x): .... print "spam " * x .... def ham(self, x): .... print "ham * %s" % x .......
17
2330
by: Picho | last post by:
Hi all, I popped up this question a while ago, and I thought it was worth checking again now... (maybe something has changed or something will change). I read this book about component...
4
1944
by: MPF | last post by:
When designing a n-tier architecture, what is the preferred method/function accessibility? <Specifically for asp.net apps> A private constructor and shared/static methods & functions? A public...
3
1762
by: rickeringill | last post by:
Hi comp.lang.javascript, I'm throwing this in for discussion. First up I don't claim to be any sort of authority on the ecmascript language spec - in fact I'm a relative newb to these more...
26
2500
by: Cliff Williams | last post by:
Can someone explain the pros/cons of these different ways of creating a class? // 1 function myclass() { this.foo1 = function() {...} } // 2a
0
7264
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7386
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7543
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...
1
7106
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7534
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...
0
3236
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
3226
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
805
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
459
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.