The recipe in question is "Implementi ng Static Methods". It shows how to
use staticmethod(). This sentence in the Discussion section isn't clear to
me: "An attribute of a class object that starts out as a Python function
implicitly mutates into an unbound method." I'm not sure what this means,
exactly. Can anyone elaborate?
Thanks,
Chris 4 1567
Joe wrote: The recipe in question is "Implementi ng Static Methods". It shows how to use staticmethod(). This sentence in the Discussion section isn't clear to me: "An attribute of a class object that starts out as a Python function implicitly mutates into an unbound method." I'm not sure what this means, exactly. Can anyone elaborate?
Thanks, Chris
First, you might cite the actual recipe here, so people can go look:
The way a class is constructed consists of:
1) open a scope at the point where the class definition starts.
2) Collect each definition in the scope (value an name). At this
point (during the collection), you are building "normal"
functions with def.
3) When the end of the class definition is found, all of the
definitions collected in (2), along with the class name and
superclasses are used to build the actual class. This is the
moment when the normal functions created in step 2 are used
to build "unbound methods" -- the magic used to make objects
work.
Here's some code that, once you understand it, illustrates this:
class SomeClass(objec t):
def function(self, other):
print 'called with self=%s, and other =%s' % (self, other)
return self, other
pair = function(1,2) # normal during class construction
print pair # We can even see the pair.
statmeth = staticmethod(fu nction)# uses, not changes, function
pair2 = function(2,3) # Demonstrate function still works
print SomeClass.pair, SomeClass.pair2 # The class vars are there
obj = SomeClass() # make an instance
pair3 = obj.function(4) # Note only 1 arg is accepted.
print obj, pair3 # the object was used as the first arg
pair4 = SomeClass.statm eth(4, 5) # The old function behavior
pair5 = obj.statmeth(5, 6)# Also the old function behavior
pair6 = SomeClass.funct ion(obj, 7) # An "unbound method" can
# be used on the right kind of object
pair7 = SomeClass.funct ion(7, 8) # Raises an exception! An
# "unbound method" needs the correct
# kind of object as its first argument.
-Scott David Daniels Sc***********@A cm.Org
"Joe" <fr***@yeah.com > wrote in message
news:SX%Cb.5486 24$Fm2.517912@a ttbi_s04... The recipe in question is "Implementi ng Static Methods". It shows how to use staticmethod(). This sentence in the Discussion section isn't clear
to me: "An attribute of a class object that starts out as a Python function implicitly mutates into an unbound method." I'm not sure what this means, exactly. Can anyone elaborate?
Thanks, Chris
Here's an example that may help show what's going on:
class C:
def f():
print "f"
print type(f)
print type(C.f)
try:
C.f()
except TypeError, e:
print e
try:
c = C()
C.f(c)
except TypeError, e:
print e
# OUTPUT
<type 'function'>
<type 'instancemethod '>
unbound method f() must be called with C instance as first argument (got
nothing instead)
f() takes no arguments (1 given)
When the class C is evaluated the "print type(f)" statement is executed. It
shows that, at that moment, f's type is 'function'.
But when you ask, "type(C.f)" it tells you that f is an instance method.
When you try to call f using "C.f()" you're told that f is an unbound
method, that must be called with an instance of C as the first argument.
When you make a method, you usually specify the first argument as being
"self". In this case "self" would be an instance of C. So, anyway, now f
appears to expect an argument when it's called. So, we try passing in what
it appears to expect "C.f(c)", and it tells us that "f() takes no arguments
(1 given)". Heh.
I'm not exactly sure what Python's doing behind the scenes but I imagine
that it's wrapping all function definitions inside the class body: something
like
for all functions in the class:
function = unbound_method( function)
where unbound_method is a callable that maintains the original function as
an attribute. When you call the unbound_method, it delegates the call to
this function f. It's the unbound_method that expects the "instance of C as
the first argument", but when it passes the argument to its delegate
function f - well, f doesn't take any arguments, so we get an exception.
Like I said, I don't know exactly what mechanism are being employed behind
the scenes, but this is the way I try to understand what's going on.
Hopefully this is somewhat correct, and helpful,
Sean
On Mon, 15 Dec 2003 08:51:07 -0800, Scott David Daniels <Sc***********@ Acm.Org> wrote: Joe wrote: The recipe in question is "Implementi ng Static Methods". It shows how to use staticmethod(). This sentence in the Discussion section isn't clear to me: "An attribute of a class object that starts out as a Python function implicitly mutates into an unbound method." I'm not sure what this means, exactly. Can anyone elaborate?
Thanks, Chris
First, you might cite the actual recipe here, so people can go look:
The way a class is constructed consists of: 1) open a scope at the point where the class definition starts. 2) Collect each definition in the scope (value an name). At this point (during the collection), you are building "normal" functions with def. 3) When the end of the class definition is found, all of the definitions collected in (2), along with the class name and superclasses are used to build the actual class. This is the moment when the normal functions created in step 2 are used to build "unbound methods" -- the magic used to make objects work.
UIAM that is not quite accurate. The defined "normal functions" you mention
remain so until dynamically accessed as attributes of the relevant class. If you bypass the
getattr mechanism (e.g., looking in the class dict), you find that the functions are still "normal": class C(object):
... def meth(*args): print 'meth args:', args
... c = C() C.meth
<unbound method C.meth> c.meth
<bound method C.meth of <__main__.C object at 0x00902410>>
but this way you see the plain old function: C.__dict__['meth']
<function meth at 0x009050B0>
if you use getattr, you can see the attribute magic: getattr(C,'meth ')
<unbound method C.meth>
and via an instance: getattr(c,'meth ')
<bound method C.meth of <__main__.C object at 0x00902410>>
calling the plain function: C.__dict__['meth'](1,2,3)
meth args: (1, 2, 3)
trying the same as class attribute, which gets you the unbound method: getattr(C,'meth ')(1,2,3)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method meth() must be called with C instance as first argument (got int insta
nce instead)
you can pass the instance explicitly: getattr(C,'meth ')(c,1,2,3)
meth args: (<__main__.C object at 0x00902410>, 1, 2, 3)
you can make a global binding to the plain function: gm = C.__dict__['meth'] gm(1,2,3)
meth args: (1, 2, 3)
you can add a method dynamically to the class: C.m2 = lambda *args:args
and the getattr magic will do its thing: C.m2
<unbound method C.<lambda>> c.m2
<bound method C.<lambda> of <__main__.C object at 0x00902410>> c.m2(1,2,3)
(<__main__.C object at 0x00902410>, 1, 2, 3) C.m2(1,2,3)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method <lambda>() must be called with C instance as first argument (got int i
nstance instead) C.m2(c,1,2,3)
(<__main__.C object at 0x00902410>, 1, 2, 3)
You can also define descriptors that will intercept the getattr magic and alter the behavior,
if you want to.
Regards,
Bengt Richter This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Cameron Laird |
last post by:
QOTW: "I'm starting with Python and I find it really great! It's ... natural!"
Lupe
http://groups.google.com/groups?selm=mailman.539.1068218589.702.python-list%40python.org
"I used to default to the widely-held position that 'language wars' are mostly
content-free 'religious' arguments, but experience has taught me otherwise.
There are big, important, differences in programmer efficiency, in
computer-resource efficiency, and in...
|
by: John J Lee |
last post by:
QOTW: "...simple genexps will work fine anyway almost all the time, so
it doesn't appear to matter much that devious uses will have nightmarish
semantics." -- Tim Peters on Generator Expressions
"It looks like ... a developer's cookbook (eg. the O'Reilly Python
cookbook) but with less Reilly and more "Oh?"."
-- Paul Boddie, on the user-commented PHP documentation
Andrew Bennetts discovers, without realising it, an obscure-but-useful
|
by: Peter Otten |
last post by:
QOTW: "I worry about Python losing its KISS principle. Python 2.2 has been
ported to the Nokia Series 60 platform, which has something like 8-16 MB of
RAM available. I'm sure the footprint growth of Python 2.3 and 2.4 gives
those developers nightmares already when they are thinking of tracking later
versions..." - Guido van Rossum
"Everyone knows that any scripting language shootout that doesn't show
Python as the best language is...
|
by: Alex Martelli |
last post by:
Greetings, fellow Pythonistas!
We (Alex Martelli, David Ascher and Anna Martelli Ravenscroft) are in
the process of selecting recipes for the Second Edition of the Python
Cookbook. Please contribute your recipes (code and discussion), along
with comments on and ratings of existing recipes, to the cookbook site,
http://aspn.activestate.com/ASPN/Cookbook/Python , and do it *now*!
The Python Cookbook is a collaborative collection of your...
|
by: Simon Brunning |
last post by:
QOTW: "I think my code is clearer, but I wouldn't go so far as to say I'm
violently opposed to your code. I save violent opposition for really
important matters like which text editor you use." - Roy Smith
"You need to recursively subdivide the cake until you have a piece small
enough to fit in your input buffer. Then the atomicity of the cake-ingestion
operation will become apparent." - Scott David Daniels
Various Python Meetup...
| |
by: Simon Brunning |
last post by:
QOTW: "The security 'droids have decided that since the MS Office Suite is a
'standard' application then software written in MS Office VBA must be 'safe.'
Any other development environments (such as Java, Perl, Cygwin) are 'unsafe'
and can't be installed." - Peter Olsen
"There's nothing wrong with open source projects catering to a market, and
there's nothing wrong with running open source software on a proprietary
operating system." -...
|
by: Simon Brunning |
last post by:
QOTW: "It's not perfect, but then nobody in this thread has offered
anything even remotely resembling perfect documentation for regular
expressions yet. <wink>" - Peter Hansen
"Python's flavor of OO is perfectly valid and usable, even though it
doesn't follow the Java Holy Bible of Object Orientation (gasp!)" - Hans Nowak
"It's highly arguable if Python is "better" than C#, but from a
control-your-own-destiny angle, Python is a...
|
by: Simon Brunning |
last post by:
QOTW: "As you learn Python, you will find that your PHP code will
improve, possibly becoming more and more concise until it disappears
completely." - Jorey Bump
(Responding to a quotaton of Sturgeon's law: "Ninety percent of
everything is crap.") "fwiw, this is of course why google displays 10
results on the first page. according to the law, one of them is always
exactly what you want." - Fredrik Lundh
|
by: TechBookReport |
last post by:
TechBookReport (http://www.techbookreport.com) has just published a
review of the Python Cookbook. This is an extract from the full review:
We're big fans of cookbooks here at TechBookReport, whether its Java,
XSLT or Linux, they're a great way of pulling together lots of useful
snippets of code and technique in one place. For the beginner they
provide instant advice, usable code and a way into new areas. They're
also a great way to find...
|
by: Simon Brunning |
last post by:
QOTW: "" - John Machin, snipping a section of Perl code.
"What sort of programmer are you? If it works on your computer, it's done,
ship it!" - Grant Edwards
Guido invites us to comment on PEP 343. This Python Enhancement
Proposal includes a 'with' statement, allowing you simply and
reliably wrap a block of code with entry and exit code, in which
resources can be acquired and released. It also proposes enhancements
|
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,...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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,...
|
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...
|
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 then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |