473,672 Members | 2,597 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 1324
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.w eb.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(se lf.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******** *************@n ews.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
10709
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. For example if you have an Employee class rather then instantiating an instance you call a static method 'GetEmployees' and it returns a List of Employee objects. I'm looking for what other people are doing and if you feel this is a good or bad...
99
5881
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 important changes, so in this thread I would like to focus on that issue alone. I have edited the Proposed Syntax example below to take out the changes unecessary to this discussion. I left in the change of "instance variable" syntax (...
0
2342
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 Methods Version: $Revision: 1.34 $ Last-Modified: $Date: 2004/09/03 09:32:50 $ Author: Kevin D. Smith, Jim Jewett, Skip Montanaro, Anthony Baxter
51
6960
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 maybe even just declare an interface, with no methods implemented). Right now, you don't really have a way to do it. You can leave the methods with a "pass", or raise a NotImplementedError, but even in the best solution that I know of,
8
2939
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 after the class was modified. I need this to work for both old ('classic') and new style classes, at both 2.3 and 2.4. I of course want to avoid side effects, and to make the solution as light-weight as possible.
11
2286
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 .... py> C().spam(3) spam spam spam
17
2348
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 oriented design (owreilly - Juval Lowy), and it was actually very nice. The book goes on about how we should use Interfaces exposure instead of classes (this is my terminology and english is not my language so I hope you understand what I'm on about...).
4
1954
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 constructor and non-shared/static methods & functions? Are there any drawbacks with regards to performance with either model? Thanks,
3
1774
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 esoteric uses (abuses?) of the language. I've been working from the oft quoted resource http://www.crockford.com/javascript/private.html. During my first serious attempt at using the knowledge acquired from this page, I ran up against the problem...
26
2531
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
8502
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8418
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8943
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8638
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8696
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6254
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4438
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2836
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 we have to send another system
2
1834
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.