473,714 Members | 4,502 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

functions, classes, bound, unbound?

Here is some example code that produces an error:

class Test(object):
def greet():
print "Hello"

t = Test()
t.greet()
TypeError: greet() takes no arguments (1 given)

Ok. That makes sense. t.greet() is a "bound method", so something
automatically relays the instance object to greet(), and since greet()
is defined with no parameters-->Error.

Hmmm...I know from testing several examples that if I call a function
that's defined inside a class, and I use the class name preceding the
function call, then I have to send the instance manually. So, based
on that error message, I'll just call the method using the class name
and not send the instance object:

Test.greet()

TypeError: unbound method greet() must be called with Test instance as
first argument (got nothing instead)

Mar 25 '07 #1
14 3032
On 24 Mar 2007 20:24:36 -0700, 7stud <bb**********@y ahoo.comwrote:
Here is some example code that produces an error:
[snip]

Why do people absolutely *love* to do weird and ugly things with
Python? Contests apart, I don't see lots of people trying this kind of
things on other (common) languages.

Say with me: "Python is powerful, but I'll use that power *only* for
beautiful and straightforward code."

Further reading:
http://www.python.org/doc/Humor.html#zen

--
Felipe.
Mar 25 '07 #2
On Sat, 24 Mar 2007 20:24:36 -0700, 7stud wrote:
Here is some example code that produces an error:

class Test(object):
def greet():
print "Hello"

t = Test()
t.greet()
TypeError: greet() takes no arguments (1 given)

Ok. That makes sense. t.greet() is a "bound method", so something
automatically relays the instance object to greet(), and since greet()
is defined with no parameters-->Error.

Hmmm...I know from testing several examples that if I call a function
that's defined inside a class, and I use the class name preceding the
function call, then I have to send the instance manually. So, based
on that error message, I'll just call the method using the class name
and not send the instance object:

Test.greet()

TypeError: unbound method greet() must be called with Test instance as
first argument (got nothing instead)

Is there a question hidden there somewhere, or are you just reporting on a
fact you have learned and are excited about?
Instance methods always need a self parameter, even if you call them from
the class. That's why you have to provide the instance by hand if you call
them from the class.

If you are trying to create a method that doesn't take a self argument,
have a look at the staticmethod function. There's also a classmethod
function as well.

--
Steven.

Mar 25 '07 #3
7stud wrote:
Here is some example code that produces an error:

class Test(object):
def greet():
print "Hello"

t = Test()
t.greet()
TypeError: greet() takes no arguments (1 given)
[snip]
Test.greet()

TypeError: unbound method greet() must be called with Test instance as
first argument (got nothing instead)
Methods in a class are generally expected to take an instance as their
first argument, but your greet() method takes no arguments. This is
because classes don't invoke the function directly, they convert it to
an 'unbound method' object::
>>class Test(object):
... def greet():
... print 'Hello'
...
>>Test.greet
<unbound method Test.greet>
>>Test.greet( )
Traceback (most recent call last):
File "<interacti ve input>", line 1, in <module>
TypeError: unbound method greet() must be called with Test instance
as first argument (got nothing instead)

If you really want to get to the original function, there are a couple
of options. You can go through the class's __dict__, or you can wrap
your method with a @staticmethod decorator (which tells the class not to
wrap the function when you try to use it)::
>>Test.__dict __['greet']
<function greet at 0x00E708B0>
>>Test.__dict __['greet']()
Hello
>>class Test(object):
... @staticmethod
... def greet():
... print 'Hello'
...
>>Test.greet
<function greet at 0x00E7D2F0>
>>Test.greet( )
Hello

STeVe
Mar 25 '07 #4
...classes don't invoke the function directly, they convert it to
an 'unbound method' object::
>>class Test(object):
... def greet():
... print 'Hello'
...
>>Test.greet
<unbound method Test.greet>
>>Test.greet( )
Traceback (most recent call last):
File "<interacti ve input>", line 1, in <module>
TypeError: unbound method greet() must be called with Test instance
as first argument (got nothing instead)
I think I found the rule in the GvF tutorial, which is essentially
what the error message says:
-------
When an unbound user-defined method object is called, the underlying
function (im_func) is called, with the restriction that the first
argument must be an instance of the proper class (im_class) or of a
derived class thereof.
--------

So, if you call a function using the syntax TheClass.theMet hod(),
then you are required to use an instance object as an argument.

In section 3.2 The Standard Class Hierarchy, it also says this:
-------
When a user-defined method object is created by retrieving a user-
defined function object from a class, its im_self attribute is None
and the method object is said to be unbound. When one is created by
retrieving a user-defined function object from a class via one of its
instances, its im_self attribute is the instance, and the method
object is said to be bound.
--------

In that first sentence, is he talking about retrieving the user-
defined function object from the class using the class name, e.g:

MyClass.someFun c

Is there some other way to retrieve a user-defined function object
from a class other than using the class name or an instance?

If you really want to get to the original function, there are a couple
of options.
No. Just trying to figure out how some things work.

Mar 25 '07 #5
On Mar 25, 9:13 am, "7stud" <bbxx789_0...@y ahoo.comwrote:
MyClass.someFun c

Is there some other way to retrieve a user-defined function object
from a class other than using the class name or an instance?
What Steven B. already said, MyClass.__dict_ _['someFunc'], is a
different way than MyClass.someFun c that produces different results.
Since the method is an attribute of a class, what other kinds of means
are you expecting to be possible?

You can use reflection to dig up MyClass-object from the module
dictionary if referring to object or class by name in the code is
something you want to get rid of.

Mar 25 '07 #6
On Mar 25, 3:00 am, irs...@gmail.co m wrote:
On Mar 25, 9:13 am, "7stud" <bbxx789_0...@y ahoo.comwrote:
MyClass.someFun c
Is there some other way to retrieve a user-defined function object
from a class other than using the class name or an instance?

What Steven B. already said, MyClass.__dict_ _['someFunc'], is a
different way than MyClass.someFun c that produces different results.
That doesn't seem to fit what GvR was talking about. From this
example:

class Test(object):
def greet():
print "Hello"

methObj = Test.__dict__["greet"]
print methObj.im_self

I get this output:

Traceback (most recent call last):
File "test1.py", line 7, in ?
print methObj.im_self
AttributeError: 'function' object has no attribute 'im_self'

So it doesn't look like a method object gets created when you retrieve
a function from a class like that. Compare to:

class Test(object):
def greet():
print "Hello"

methObj = Test.greet
print methObj.im_self

output:
None
Since the method is an attribute of a class, what other kinds of means
are you expecting to be possible?
I'm just wondering why in this description:
----
When a user-defined method object is created by retrieving a user-
defined function object from a class, its im_self attribute is None
and the method object is said to be unbound. When one is created by
retrieving a user-defined function object from a class via one of its
instances, its im_self attribute is the instance, and the method
object is said to be bound.
-----
GvR didn't explicitly mention using the class name to retrieve the
function object in the first sentence. It seems to imply there are
other ways to retrieve the function object from the class that cause a
method object to be created.

Mar 25 '07 #7
En Sun, 25 Mar 2007 17:22:36 -0300, 7stud <bb**********@y ahoo.com>
escribió:
On Mar 25, 3:00 am, irs...@gmail.co m wrote:
>On Mar 25, 9:13 am, "7stud" <bbxx789_0...@y ahoo.comwrote:
Is there some other way to retrieve a user-defined function object
from a class other than using the class name or an instance?

What Steven B. already said, MyClass.__dict_ _['someFunc'], is a
different way than MyClass.someFun c that produces different results.

methObj = Test.__dict__["greet"]
print methObj.im_self

Traceback (most recent call last):
File "test1.py", line 7, in ?
print methObj.im_self
AttributeError: 'function' object has no attribute 'im_self'
Because this way, you get a function, not a method. I'd say "read
something about descriptors" but...

Nicolas Bourbaki [a collective of french mathematicians writing under that
alias] said on a book about set theory: Any school boy can understand all
of this with a minimum of effort, but for truly understanding what we are
talking about, around four years of prior training on mathematics may be
required. (I can't find the exact citation).

I suggest first learn to use Python and then try to understand how it does
what it does, along the way, and looking for answers when you have a
question.

--
Gabriel Genellina

Mar 25 '07 #8
On Mar 25, 9:13 am, "7stud" <bbxx789_0...@y ahoo.comwrote:
Is there some other way to retrieve a user-defined function object
from a class other than using the class name or an instance?
On Mar 25, 3:00 am, irs...@gmail.co m wrote:
What Steven B. already said, MyClass.__dict_ _['someFunc'], is a
different way than MyClass.someFun c that produces different results.
7stud wrote:
That doesn't seem to fit what GvR was talking about. From this
example:

class Test(object):
def greet():
print "Hello"

methObj = Test.__dict__["greet"]
print methObj.im_self

I get this output:

Traceback (most recent call last):
File "test1.py", line 7, in ?
print methObj.im_self
AttributeError: 'function' object has no attribute 'im_self'

Yep. The thing in the class __dict__ is the original *function*. The
thing you get from something like ``Test.greet`` is the *method*.
Here's another way of looking at it::
>>class Test(object):
... pass
...
>>def greet():
... print 'Hello'
...
>>greet
<function greet at 0x00E718B0>
>>Test.greet = greet
Test.__dict __['greet']
<function greet at 0x00E718B0>
>>Test.__dict __['greet'] is greet
True

Note that ``Test.__dict__['greet']`` is the ``greet`` *function*, not
some wrapper of that function. When you access the class attribute
normally, Python creates an 'unbound method' object::
>>Test.greet
<unbound method Test.greet>
>>Test.greet is greet
False
>>Test.greet.im _func
<function greet at 0x00E718B0>
>>Test.greet.im _func is greet
True

See that ``Test.greet`` gives you an 'unbound method' object which just
wraps the real 'function' object (which is stored as the 'im_func'
attribute)? That's because under the covers, classes are actually using
doing something like this::
>>Test.__dict __['greet'].__get__(None, Test)
<unbound method Test.greet>
>>Test.greet == Test.__dict__['greet'].__get__(None, Test)
True

So if you want to get a method from a function, you can always do that
manually yourself::
>>greet.__get__ (None, Test)
<unbound method Test.greet>

Hope that helps,

STeVe
Mar 25 '07 #9
7stud a écrit :
>...classes don't invoke the function directly, they convert it to
an 'unbound method' object::
(snip)
>
>If you really want to get to the original function, there are a couple
of options.

No. Just trying to figure out how some things work.
Most of Python's object model is documented here:

http://www.python.org/download/relea....3/descrintro/
http://users.rcn.com/python/download/Descriptor.htm
HTH

Mar 26 '07 #10

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

Similar topics

7
1801
by: Rim | last post by:
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'
2
1420
by: Jacek Generowicz | last post by:
Functions defined in Python have type types.FunctionType, and are descriptors whose __get__ method turns them into bound or unbound methods. Functions defined in extension modules have type types.BuiltinFunctionType, and have no __get__ method. Adding them as attributes to classes and calling them through an instance of the class does not result in them being called as methods: self is lost. What's the simplest way of getting around this...
99
5899
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 (...
15
1483
by: Paulo da Silva | last post by:
How do I program something like the folowing program? PYTHON claims it doesn't know about 'foo' when initializing K! The only way I got this to work was doing the init of K in the __init__ func. But this runs everytime for each object! When using the name of the function without 'foo', I don't know how to call it! Thanks for any help. #! /bin/env python
21
3576
by: ron | last post by:
Why doesn't this work? >>> def foo(lst): .... class baz(object): .... def __getitem__(cls, idx): return cls.lst .... __getitem__=classmethod(__getitem__) .... baz.lst = lst .... return baz .... >>> f = foo()
19
4106
by: James Fortune | last post by:
I have a lot of respect for David Fenton and Allen Browne, but I don't understand why people who know how to write code to completely replace a front end do not write something that will automate the code that implements managing unbound controls on forms given the superior performance of unbound controls in a client/server environment. I can easily understand a newbie using bound controls or someone with a tight deadline. I guess I need...
0
8808
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
8712
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
9316
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
9077
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
9023
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...
0
7954
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5959
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();...
1
3160
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
3
2113
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.