473,727 Members | 2,008 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

difference between class methods and instance methods

I've done some C++ and Java in the past, and have recently learned
a fair amount of Python. One thing I still really don't get though
is the difference between class methods and instance methods. I
guess I'll try to narrow it down to a few specific questions, but
any further input offered on the subject is greatly appreciated:

1. Are all of my class's methods supposed to take 'self' as their
first arg?

2. Am I then supposed to call them with MyClass.foo() or instead:

bar = MyClass()
bar.foo()
?

3. Is "bound method" a synonym for instance method?

4. Is "unbound method" a synonym for class method?

And if anyone's *really* daring:
Where do the so-called "static methods" fit into all this?
By the name of them, it sounds like the same thing as class
methods...

Much thanks,
---J

--
--- if replying via email, remove zees ---
Jul 18 '05 #1
18 6949
John M. Gabriele wrote:
1. Are all of my class's methods supposed to take 'self' as their
first arg?
If by "class's methods" you mean methods on which you called
classmethod, then no, they shouldn't take a 'self' parameter, they
should take a 'cls' parameter because the first argument to the function
will be the class:

class C(object):
@classmethod
def f(cls, *args):
# do stuff

Undecorated methods (e.g. those that are not wrapped with classmethod or
staticmethod) should, on the other hand, take a 'self' parameter.
2. Am I then supposed to call them with MyClass.foo() or instead:

bar = MyClass()
bar.foo()
Classmethods should be called from the class. Python allows you to call
them from the instance, but this almost never does what you want, e.g.:

py> d = {}
py> d.fromkeys(rang e(4))
{0: None, 1: None, 2: None, 3: None}
py> d
{}

Note that 'd' is not updated -- I called a classmethod, not an
instancemethod. If I had called dict.fromkeys instead, this would have
been clearer.
3. Is "bound method" a synonym for instance method?

4. Is "unbound method" a synonym for class method?
No. To simplify things a little[1], a "bound method" is an instance
method that has been associated with a specific instance, and an
"unbound method" is an instance method that has not been associated with
a specific instance. Consider the difference between str.join and ''.join:

py> str.join
<method 'join' of 'str' objects>
py> ', '.join
<built-in method join of str object at 0x01233620>
py> str.join(['a', 'b', 'c'])
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: descriptor 'join' requires a 'str' object but received a 'list'
py> ', '.join(['a', 'b', 'c'])
'a, b, c'
py> str.join(', ', ['a', 'b', 'c'])
'a, b, c'

In the example above, you can see that str.join is an "unbound method"
-- when I try to call it without giving it an instance, it complains.
On the other hand, ', '.join is a "bound method" because it has been
bound to a specific instance of str (in this case, the instance ', ').
When I call it without an instance, it doesn't complain because it's
already been bound to an instance.
Where do the so-called "static methods" fit into all this?
By the name of them, it sounds like the same thing as class
methods...


Staticmethods, like classmethods, are associated with the class object,
not the instance objects. The main difference is that when a
staticmethod is called, no additional arguments are supplied, while when
a classmethod is called, a first argument, the class, is inserted in the
argument list:

py> class C(object):
.... @classmethod
.... def f(*args):
.... print args
.... @staticmethod
.... def g(*args):
.... print args
....
py> C.f(1, 2, 3)
(<class '__main__.C'>, 1, 2, 3)
py> C.g(1, 2, 3)
(1, 2, 3)

STeVe

[1] Technically, I think classmethods could also considered to be "bound
methods" because in this case, the method is associated with a specific
instance of 'type' (the class in which it resides) -- you can see this
in the first argument that is supplied to the argument list of a
classmethod.
Jul 18 '05 #2
John M. Gabriele wrote:
I've done some C++ and Java in the past, and have recently learned
a fair amount of Python. One thing I still really don't get though
is the difference between class methods and instance methods. I
guess I'll try to narrow it down to a few specific questions, but
any further input offered on the subject is greatly appreciated:
I'll try not to cover the same ground as Steven did in his reply.

1. Are all of my class's methods supposed to take 'self' as their
first arg? consider this:
class Demo(object): def foo(self, x):
print self, x
@classmethod
def clsmethod(cls, x):
print cls, x
@staticmethod
def stmethod(x):
print x

instance = Demo()
Calling a bound method, you don't pass an explicit self parameter, but the
method receives a self parameter:
bound = instance.foo
bound(2) <__main__.Dem o object at 0x00B436B0> 2

Note that it doesn't matter whether you call instance.foo(2) directly, or
bind instance.foo to a variable first. Either will create a *new* bound
method object, and the correct instance is used for the call. This is
significantly different from languages such as C++ and Javascript which are
a real pain if you want to use a method as a callback.

Calling an unbound method, you pass a self parameter explicitly (and it
must be an instance of the class, *or an instance of a subclass*:
unbound = Demo.foo
unbound(instanc e, 2) <__main__.Dem o object at 0x00B436B0> 2

Again is doesn't matter whether you do this in one step or two. The usual
case for using an unbound method is when you have overridden a method in a
derived class and want to pass the call on to a base class. e.g.
class Derived(Demo): def foo(self, x):
Demo.foo(self, x)

A class method is usually called through the class rather than an instance,
and it gets as its first parameter the actual class involved in the call:
Demo.clsmethod( 2) <class '__main__.Demo' > 2 Derived.clsmeth od(2) <class '__main__.Deriv ed'> 2

You can call a class method using an instance of the class, or of a
subclass, but you still the get class passed as the first parameter rather
than the instance:
d = Derived
d.clsmethod(2) <class '__main__.Deriv ed'> 2

A common use for class methods is to write factory functions. This is
because you can ensure that the object created has the same class as the
parameter passed in the first argument. Alternatively you can use class
methods to control state related to a specific class (e.g. to count the
number of instances of that exact class which have been created.)

There is no equivalent to a class method in C++.

Static methods are like static methods in C++. You can call them through
the class or a subclass, or through an instance, but the object used in the
call is not passed through to the method:
Demo.stmethod(2 ) 2 instance.stmeth od(2) 2 Derived.stmetho d(2) 2 d.stmethod(2) 2


2. Am I then supposed to call them with MyClass.foo() or instead:

bar = MyClass()
bar.foo()
?
If you have an instance then use it. If the class method is a factory then
you might want to create a new object of the same type as some existing
object (but not a simple copy since you won't get any of the original
object's state). Mostly though you know the type of the object you want to
create rather than having an existing instance lying around.

3. Is "bound method" a synonym for instance method?
Close but not quite. It is a (usually transient) object created from an
unbound instance method for the purposes of calling the method.
4. Is "unbound method" a synonym for class method?
Definitely not.

And if anyone's *really* daring:
Where do the so-called "static methods" fit into all this?
By the name of them, it sounds like the same thing as class
methods...


See above.

Jul 18 '05 #3
Steven Bethard wrote:
John M. Gabriele wrote:
1. Are all of my class's methods supposed to take 'self' as their
first arg?

If by "class's methods" you mean methods on which you called
classmethod, then no, they shouldn't take a 'self' parameter, they
should take a 'cls' parameter because the first argument to the function
will be the class:

class C(object):
@classmethod
def f(cls, *args):
# do stuff


Sorry -- I'm not as far along as you suspect. :) I've
never yet seen this "@classmeth od" syntax. I'm supposing that
it's part of this so-called "new-style" class syntax.

When I ask "are all my class's methods...", I mean, when
I'm writing a class statement and the def's therein -- are
all those def's supposed to take 'self' as their first arg.

From your reply, I gather that, unless I'm using this special
syntax (@classmethod or @staticmethod), all my def's are supposed
to take 'self' as their first arg.
Undecorated methods (e.g. those that are not wrapped with classmethod or
staticmethod) should, on the other hand, take a 'self' parameter.
Ok. Check.

So then, are all def's -- that take 'self' as their first --
argument -- in a class statement, instance methods?

2. Am I then supposed to call them with MyClass.foo() or instead:

bar = MyClass()
bar.foo()

Classmethods should be called from the class. Python allows you to call
them from the instance, but this almost never does what you want, e.g.:

py> d = {}
py> d.fromkeys(rang e(4))
{0: None, 1: None, 2: None, 3: None}
py> d
{}

Note that 'd' is not updated -- I called a classmethod, not an
instancemethod. If I had called dict.fromkeys instead, this would have
been clearer.


Right. An important lesson in C++ as well.

3. Is "bound method" a synonym for instance method?

4. Is "unbound method" a synonym for class method?

No. To simplify things a little[1], a "bound method" is an instance
method that has been associated with a specific instance, and an
"unbound method" is an instance method that has not been associated with
a specific instance.


Ok! Now I'm making some headway. *This* is getting
at the crux of the biscuit.

Consider the difference between str.join and ''.join:

py> str.join
<method 'join' of 'str' objects>

py> ', '.join
<built-in method join of str object at 0x01233620>

Hmm... weird.
py> str.join(['a', 'b', 'c'])
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: descriptor 'join' requires a 'str' object but received a 'list'

Right -- 'cause there's no actual instance of a string
to do the joining. Check.
py> ', '.join(['a', 'b', 'c'])
'a, b, c'
Check.
py> str.join(', ', ['a', 'b', 'c'])
'a, b, c'
Ack! Now you're creeping me out. Looking at the doc for str.join:

| py> help( str.join )
| Help on method_descript or:
|
| join(...)
| S.join(sequence ) -> string
|
| Return a string which is the concatenation of the strings in the
| sequence. The separator between elements is S.
|

It says that you didn't call that method correctly. Yet
it works anyway!? What's happening here?

In the example above, you can see that str.join is an "unbound method"
-- when I try to call it without giving it an instance, it complains. On
the other hand, ', '.join is a "bound method" because it has been bound
to a specific instance of str (in this case, the instance ', '). When I
call it without an instance, it doesn't complain because it's already
been bound to an instance.
Ok. I see that distinction. Thanks.
Where do the so-called "static methods" fit into all this?
By the name of them, it sounds like the same thing as class
methods...

Staticmethods, like classmethods, are associated with the class object,
not the instance objects.


That makes sense.
The main difference is that when a
staticmethod is called, no additional arguments are supplied, while when
a classmethod is called, a first argument, the class, is inserted in the
argument list:

py> class C(object):
... @classmethod
... def f(*args):
... print args
... @staticmethod
... def g(*args):
... print args
...
py> C.f(1, 2, 3)
(<class '__main__.C'>, 1, 2, 3)
py> C.g(1, 2, 3)
(1, 2, 3)

STeVe
Thanks for that nice example. It looks like you're always
supposed to call both class and static methods via the class
name (rather than an instance name). I'll read up on what
this new @classmethod and @staticmethod syntax means.
[1] Technically, I think classmethods could also considered to be "bound
methods" because in this case, the method is associated with a specific
instance of 'type' (the class in which it resides) -- you can see this
in the first argument that is supplied to the argument list of a
classmethod.


--
--- remove zees if replying via email ---
Jul 18 '05 #4
Duncan Booth wrote:
John M. Gabriele wrote:

I've done some C++ and Java in the past, and have recently learned
a fair amount of Python. One thing I still really don't get though
is the difference between class methods and instance methods. I
guess I'll try to narrow it down to a few specific questions, but
any further input offered on the subject is greatly appreciated:

I'll try not to cover the same ground as Steven did in his reply.


Thanks for taking the time to reply Duncan.
1. Are all of my class's methods supposed to take 'self' as their
first arg?
consider this:

class Demo(object):

def foo(self, x):
print self, x
@classmethod
def clsmethod(cls, x):
print cls, x
@staticmethod
def stmethod(x):
print x

instance = Demo()
Calling a bound method, you don't pass an explicit self parameter, but the
method receives a self parameter:
bound = instance.foo
bound(2)

<__main__.Dem o object at 0x00B436B0> 2

Note that it doesn't matter whether you call instance.foo(2) directly, or
bind instance.foo to a variable first. Either will create a *new* bound
method object, and the correct instance is used for the call.


Za! What do you mean, "create a new bound method object"? I *already*
created that method when I def'd it inside the 'class Demo' statement,
no?
This is
significantly different from languages such as C++ and Javascript which are
a real pain if you want to use a method as a callback.

Calling an unbound method, you pass a self parameter explicitly (and it
must be an instance of the class, *or an instance of a subclass*:
unbound = Demo.foo
unbound(instanc e, 2)

<__main__.Dem o object at 0x00B436B0> 2
Ahhhhhhhh! See, coming from C++, the first thing I thought
when I saw what you just wrote was, "whoops, he shouldn't be
calling that instance method via the class name -- it's a bad
habit". Now I think I see what you mean: you may call an
instance method in two ways: via an instance where you don't
pass in anything for 'self', and via the class name, where
you must supply a 'self'.
Again is doesn't matter whether you do this in one step or two. The usual
case for using an unbound method is when you have overridden a method in a
derived class and want to pass the call on to a base class. e.g.
Ok. Interesting.

class Derived(Demo):

def foo(self, x):
Demo.foo(self, x)

A class method is usually called through the class rather than an instance,
and it gets as its first parameter the actual class involved in the call:
Demo.clsmethod( 2)

<class '__main__.Demo' > 2

Derived.clsmeth od(2)

<class '__main__.Deriv ed'> 2
Check.
You can call a class method using an instance of the class, or of a
subclass, but you still the get class passed as the first parameter rather
than the instance:
d = Derived
d.clsmethod(2)

<class '__main__.Deriv ed'> 2
Ok, so it looks like it may lead to confusion if you do that.
I wonder why the language allows it...

A common use for class methods is to write factory functions. This is
because you can ensure that the object created has the same class as the
parameter passed in the first argument. Alternatively you can use class
methods to control state related to a specific class (e.g. to count the
number of instances of that exact class which have been created.)

There is no equivalent to a class method in C++.
Right. I see -- because in Python, a reference the actual class
object is implicitly passed along with the method call. Whereas,
C++ doesn't even have "class objects" to begin with.

Static methods are like static methods in C++. You can call them through
the class or a subclass, or through an instance, but the object used in the
call is not passed through to the method:
Demo.stmethod(2 )

2

instance.stmeth od(2)

2

Derived.stmetho d(2)

2

d.stmethod(2)

2

2. Am I then supposed to call them with MyClass.foo() or instead:

bar = MyClass()
bar.foo()
?

If you have an instance then use it. If the class method is a factory then
you might want to create a new object of the same type as some existing
object (but not a simple copy since you won't get any of the original
object's state). Mostly though you know the type of the object you want to
create rather than having an existing instance lying around.

3. Is "bound method" a synonym for instance method?

Close but not quite. It is a (usually transient) object created from an
unbound instance method for the purposes of calling the method.


.... hmm... bound methods get created each time you make
a call to an instance method via an instance of the given class?

4. Is "unbound method" a synonym for class method?

Definitely not.


Right. :)
And if anyone's *really* daring:
Where do the so-called "static methods" fit into all this?
By the name of them, it sounds like the same thing as class
methods...

See above.

--
--- remove zees if replying via email ---
Jul 18 '05 #5
John wrote:
... hmm... bound methods get created each time you make
a call to an instance method via an instance of the given class?


No, they get created when you create an actual instance of an object. So
only at construction time. Creating them means taking the unbound method
and binding the created object as first argument to the method. Thus each
instance of a class Foo with a method bar has its own instance of bar - the
bound method bar. But only one per object.
--
Regards,

Diez B. Roggisch
Jul 18 '05 #6
Diez B. Roggisch wrote:
John wrote:
... hmm... bound methods get created each time you make
a call to an instance method via an instance of the given class?

No, they get created when you create an actual instance of an object. So
only at construction time. Creating them means taking the unbound method
and binding the created object as first argument to the method. Thus each
instance of a class Foo with a method bar has its own instance of bar - the
bound method bar. But only one per object.


Ohhhhhhhh. Unlike C++, where methods are not first class objects
and you only have *one* that gets shared by all instances.

I'm getting it. Thanks for the reply. :)

---J

--
--- remove zees if replying via email ---
Jul 18 '05 #7
> Ohhhhhhhh. Unlike C++, where methods are not first class objects
and you only have *one* that gets shared by all instances.


Exactly - so unlike in c++, where you have to do ugly hacks if e.g. a C-lib
takes a callback and you want to pass an instance method, you can do that
in python. It's really great.

--
Regards,

Diez B. Roggisch
Jul 18 '05 #8
John wrote:
Steven Bethard wrote:
John M. Gabriele wrote:
class C(object):
@classmethod
def f(cls, *args):
# do stuff
Sorry -- I'm not as far along as you suspect. :) I've
never yet seen this "@classmeth od" syntax. I'm supposing that
it's part of this so-called "new-style" class syntax.


This is syntactic sugar in Python 2.4 for:

class C(object):
def f(cls, *args):
# do stuff
f = classmethod(f)

So if you'd like to check the docs, look in the builtins for classmethod
(and staticmethod):

http://docs.python.org/lib/built-in-funcs.html

From your reply, I gather that, unless I'm using this special
syntax (@classmethod or @staticmethod), all my def's are supposed
to take 'self' as their first arg.
Yup. You're of course welcome to name it whatever you like, but the
methods defined in your class (when not wrapped with classmethod,
staticmethod, etc.) will all be called with an instance of the class as
their first argument. So you need to make sure 'self' or something like
it is the first parameter to the function.
So then, are all def's -- that take 'self' as their first --
argument -- in a class statement, instance methods?
Basically, yes. (Again, assuming they're not wrapped with anything.)
Consider the difference between str.join and ''.join:

py> str.join
<method 'join' of 'str' objects>
>

py> ', '.join
<built-in method join of str object at 0x01233620>
>


Hmm... weird.


Ok, the point here is that str.join and ', '.join are not the same
object. The reason is that, when the ', ' instance of str is created,
new "bound method" objects are created for each of the instance methods
in str. These "bound methods" all know that the first argument to their
functions is ', '.
py> ', '.join(['a', 'b', 'c'])
'a, b, c'


Check.
py> str.join(', ', ['a', 'b', 'c'])
'a, b, c'

[snip] What's happening here?


str.join is the "unbound method" of the str object. So just like you
have to declare 'self' as the first argument of all your instance
methods, the writer of the str object methods also declared 'self' as
the first argumetn to str.join. So str.join looks something like:

class str(object):
...
def join(self, sequence):
...

So when you access it like str.join(...) you should be passing it an
instance and a sequence. On the other hand, the "bound method" created
for ', ' has already bound the instance, so it no longer expects the
'self' argument to be passed in.

HTH,

STeVe
Jul 18 '05 #9
John wrote:
Note that it doesn't matter whether you call instance.foo(2)
directly, or bind instance.foo to a variable first. Either will
create a *new* bound method object, and the correct instance is used
for the call.
Za! What do you mean, "create a new bound method object"? I *already*
created that method when I def'd it inside the 'class Demo' statement,
no?

The def statement creates a function.
Accessing the method through the class creates a brand new unbound method
from the function. Every access of the method through the class creates a
separate unbound method.

Accessing the method through the instance creates a brand new bound method.
Every such access creates a separate bound method.

... hmm... bound methods get created each time you make
a call to an instance method via an instance of the given class?

you've got it.
Jul 18 '05 #10

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

Similar topics

10
2844
by: Johnny Lee | last post by:
Hi, I'm new in python and I was wondering what's the difference between the two code section below: (I) class TestResult: _pass_ = "pass" _fail_ = "fail" _exception_ = "exception"
1
1510
by: Taylor | last post by:
"Static" is synonymous with "class" with regards to members (methods and fields) right? Sometimes I hear refrence to the "static method" and sometimes its refered to a "static method." Is there a subtle/grand difference between the two? For example here http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/observerpattern.asp I read
5
8732
by: Chris | last post by:
Hi, I don't get the difference between a struct and a class ! ok, I know that a struct is a value type, the other a reference type, I understand the technical differences between both, but conceptually speaking : when do I define something as 'struct' and when as 'class' ? for example : if I want to represent a 'Time' thing, containing : - data members : hours, mins, secs
5
1609
by: Diffident | last post by:
Hello All, I am designing a class based on singleton pattern. Inside this class I have multiple instance methods. My question is since there will be only one instance of this class at any instance of time in the whole application there is no use in having these methods as instance methods I can as well have static methods....correct? If I leave these methods as instance methods would they have any wrong impact on my application?
13
3356
by: dmh2000 | last post by:
I am experimenting with the interactive interpreter environments of Python and Ruby and I ran into what seems to be a fundamental difference. However I may be doing something wrong in Python. Please comment and correct me if I am wrong In both languages, you can start up the interactive interpreter ('python' and 'irb'), load source files and do stuff, like create objects and call their methods. When you want to change something, you can...
3
5647
by: John Salerno | last post by:
I've been reading up on them, but I don't quite understand how they differ in practice. I know how each is implemented, and from C# I already know what a static method is. But I won't assume that it's the same in Python. And on top of that, both the class and static methods of Python seem to do what a C# static method does, so I don't see the difference yet. Thanks.
10
5492
by: Bonzol | last post by:
vb.net Hey there, could someone just tell me what the differnce is between classes and modules and when each one would be used compared to the other? Any help would be great Thanx in advance
8
2628
by: nytimescnn | last post by:
I've read some discuession about lock() for thread-safe. I am wondering what will be the differce between below two code segment? Code 1: class A { private static Object padlock = new Object(); ...// some codes
8
20609
by: weird0 | last post by:
Can anyone explain briefly what is the difference between inheritance and polymorphism? i read and seem to forget it again and again... Can anyone along with good examples of c# explain the fundanmental concept so i can remember it forever as it is a common interview question.... Thanks in advance
0
8890
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
9402
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...
0
9259
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 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...
0
8101
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
6011
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();...
0
4785
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
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
2639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
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.