473,731 Members | 2,609 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

class method question

can you explain why python does not see difference between instance
method and class method, having the same name

>>class toto(object):
.... def f(self):
.... print('instance method')
.... @classmethod
.... def f(cls):
.... print('class method')
<bound method type.f of <class '__main__.toto' >>
class method
class method
if i do the same in ruby:
class Toto
def meth
print "instance method\n"

def Toto.meth
print "class method\n"

i = Toto.new

$ruby1.9 test_classmetho d.rb
instance method
class method

Oct 25 '06 #1
2 1390
Sylvain Ferriol wrote:
can you explain why python does not see difference between instance
method and class method, having the same name
You're trying to put two objects with the same name in the same namespace.
>>class toto(object):
... def f(self):
... print('instance method')
... @classmethod
... def f(cls):
... print('class method')
<bound method type.f of <class '__main__.toto' >>
class method
class method

if i do the same in ruby:
Python works better if you use it to write Python programs.


Oct 25 '06 #2
Sylvain Ferriol wrote:
can you explain why python does not see difference between instance
method and class method, having the same name
Because class namespaces are dicts, and you can't have duplicate keys in
dicts. It's totally unrelated to class/instance method distinction (try
with any kind of attribute, you'll get the same result : only the last
attribute is kept).
>>>class toto(object):
... def f(self):
... print('instance method')

... @classmethod
... def f(cls):
... print('class method')
<bound method type.f of <class '__main__.toto' >>
class method
class method
Also note that Python classmethods can be called on instances. Here
you're calling the same function twice.

A python object is a data structure holding references to other objects.
One of these references points to a dict (named __dict__) storing the
object's own attributes ('instance' attributes), and another one (named
__class__) points to the class object - which is itself an object that
holds references to it's parent classes.

When a name is looked up on an object, the name is first looked up in
the object's __dict__, then in the class, then in the class's parent

If you want a Ruby-like behaviour, it's still possible, but you have to
do it by manually:

import types

class Rubysh(object):
def test(cls):
print "in classmethod test, cls : %s" % cls

def __init__(self):
def test(self):
print "in instance method test, self : %s" % self
self.test = types.MethodTyp e(test, self, self.__class__)

r = Rubysh()

Also note that most python programmers may find this a bit confusing,
since they'd expect Rubish.test() and r.test() to resolve to the same
if i do the same in ruby:
You're not "doing the same", you're doing something that *looks* the same.

While they look quite similar at first sight - and indeed share a lot of
characteristics (lightweight, highly dynamic, hi-level object languages)
-, Python and Ruby are very different beasts under the hood. So beware :
superficial similarities can hide very different meanings and behaviours.

bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Oct 25 '06 #3

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

Similar topics

by: Kerry Neilson | last post by:
Hi, Really hung up on this one. I'm trying to get all the fields of a dictionary to be unique for each class: class A { my_dict = dict_entry = { 'key1':0, 'key2':0 } __init__(self): for x in range(10):
by: He Shiming | last post by:
Hi, I've got a question regarding class inheritance. The following code reproduces the problem I'm dealing with: class IBase { public: virtual void Method(void)=0; };
by: Oriane | last post by:
Hi, I'm currently a method attribute which is used to check the "validity" of this method against a rule. I wrote the isValid method, to be used inside the otriginal method: For instance: // Following is Csharp code private void functionT12 ()
by: Ray Dukes | last post by:
What I am looking to do is map the implementation of interface properties and functions to an inherited method of the base class. Please see below. '**************************************************************************** ' Issues '****************************************************************************
by: roland.bali | last post by:
Hi, Here is the basic setup, my base class is Shoe which has a child class called Sandal. I would like to create objects by calling Sandal.Load. But without overloading Load in Sandal and sending the Sandal type to the base class I can not instantiate a Sandal class from within Shoe. Public Class Shoe Public Shared Function Load() As Object return ?????
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);
by: Ben | last post by:
Hi, i defined a function in the base class 'ford' and the same function (with different output) in subclass "peugeot". I first put 'Overridable function' in the base class and 'Overrides function' in the subclass. It works. Then i removed them in both classes, like here below: Public Class ford .....
by: Brad Pears | last post by:
Here is a simple OO design question... I have a Contract class. The user can either save an existing contract or they start off fresh with a blank contract, fill in the data and then save a "new" contract. I have a method in my contract class called "Save" which is called like this... dim oContract as new Contract
by: =?Utf-8?B?dG9iaXdhbl9rZW5vYmk=?= | last post by:
In the following code, calling CallTestMethod() from an instance of the derived class (the base is abstract and we can never instantiate it), referencing 'base.TestMethod()' actually calls 'TestMethod()' in the base class, but referencing 'this.CallTestMethod()' (defined in the base class) references the overriding method, not the method defined within the base class, making calling 'TestMethod()' seem virtually impossible (pun intended). ...
by: K Viltersten | last post by:
Suppose there is the following class structure. class S {...} class A : S {...} class B : S {...} class A1 : A {void m(){...}} class B1 : B {void m(){...}} class B2 : B {...} Just to clarify the issue. A1 and B1 share a method (void m() ) AND B2 doesn't have that
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...
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...
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: 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...
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: 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...
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: 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.