473,811 Members | 2,714 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

difference between class and static methods?

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.
Apr 18 '06 #1
3 5651
In <gP************ ******@news.tuf ts.edu>, John Salerno wrote:
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.


The difference is that the classmethod gets the class as first argument
much like self in instance methods.

class A:
def __init__(self, data):
print 'A'
self.data = data

@classmethod
def from_file(cls, filename):
# read data
return cls(data)

class B(A):
def __init__(self, data):
print 'B'
self.data = data

If you call `B.from_file('s pam.xyz')` now, the `from_file()` method
inherited from class `A` is called but with `B` as the first argument so
it returns an instance of `B`.

A staticmethod is just a function attached to a class without any "magic".

Ciao,
Marc 'BlackJack' Rintsch
Apr 18 '06 #2
Marc 'BlackJack' Rintsch wrote:
If you call `B.from_file('s pam.xyz')` now, the `from_file()` method
inherited from class `A` is called but with `B` as the first argument so
it returns an instance of `B`.

A staticmethod is just a function attached to a class without any "magic".


So a class method is specifically for using the class name itself as an
object in the method? If that's the case, then it makes some sense now.
I guess the reason I didn't get it before is that this is a feature of
dynamic languages, right? And something that couldn't have been done in
C# anyway?
Apr 18 '06 #3

"John Salerno" wrote...
[...]
So a class method is specifically for using the class name itself as an
object in the method? If that's the case, then it makes some sense now.
I guess the reason I didn't get it before is that this is a feature of
dynamic languages, right? And something that couldn't have been done in
C# anyway?


Yes, almost. You can think about a class method as about something that
can be called even if no object of that class was created. It can be called
through the class name. But it can also be called through the instance
(the object). On the other hand, the normal method can be called only
through the object. It does not belong to the class -- see below.

The class method has access to the class variables, but not to the
instance variables (no instance may exists) -- not shown here.

Try the following script (I have stored it as a.py)
---------------------------------------------------
class C:
def __init__(self):
print 'Instance of the class C was created.'

@classmethod
def myClassMethod(c ls):
print 'myClassMethod called'

def myMethod(self):
print 'myMethod (i.e. the normal one) was called.'

C.myClassMethod ()

obj = C()
obj.myClassMeth od()
obj.myMethod()

C.myMethod() # cannot be done, error.
---------------------------------------------------

And run it

C:\tmp>python a.py
myClassMethod called
Instance of the class C was created.
myClassMethod called
myMethod (i.e. the normal one) was called.
Traceback (most recent call last):
File "a.py", line 18, in ?
C.myMethod()
TypeError: unbound method myMethod() must be called with C instance as first
argument (got nothing instead)

pepr
Apr 19 '06 #4

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

Similar topics

18
6962
by: John M. Gabriele | last post by:
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...
1
1513
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
6
1823
by: Baris | last post by:
Given the C# code below, can anyone think of a better class design? What really gets my goat is that the code within derived classes D1 and D2 is identical and in my mind should be refactored into a base class, but how can I move this particular 'shared functionality' into a base class? If anyone can suggest a better newsgroup for this, such as one focussed primarily on C# class design, please let me know.
28
4650
by: Dennis | last post by:
I have a function which is called from a loop many times. In that function, I use three variables as counters and for other purposes. I can either use DIM for declaring the variables or Static. Would the performance be better using Static versus Dynamic. I would think it would be quicker with STATIC declarations since the variables would only have to be created once. Can anyone confirm this. Thanks. -- Dennis in Houston
2
5487
by: Vivek Ragunathan | last post by:
Hi Are the members in a static class in C# class synchronized for multiple thread access. If yes, are all static members in a C# class auto synchronized ? Regards Vivek Ragunathan
10
5502
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
2633
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
9
5852
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to the static Parse method of the conversion class. if (InValue is string) return T.Parse((string)InValue); else return base.ConvertFrom(context, culture, InValue);
17
1984
by: =?Utf-8?B?SmVzcGVyLCBEZW5tYXJr?= | last post by:
What is the difference of == and Object.Equals() If I want to query werther to pointers are pointing to same instance, do I use == or Objects.Equals? foo a,b; if ( a == b ) ... or if (a.Equals(b))
0
9605
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
10386
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...
1
10398
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
10133
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
7669
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
6889
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
5554
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5692
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3865
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.