0

Suppose we declare a static method with same name in different classes. Is it possible?

If it is, then how and which function will be called?

class abc:
    @staticmethod
    def xyz():
        print 'class_abc'
class abc1:
    @staticmethod
    def xyz():
        print 'class_abc1'
class abc2:
    @staticmethod
    def xyz():
        print 'class_abc2'

So what's the output and how we can call different functions of different classes?

martineau
  • 119,623
  • 25
  • 170
  • 301
Anurag Misra
  • 1,516
  • 18
  • 24

3 Answers3

2

You are having three classes with xyz() function in each class. But there is no relationship in these classes as they are not inheriting each other. So the answer is simple: xyz() will be called of the class which is calling the method.

For example: abc.xyz() will call the xyz() function of abc class. Similarly you can make call to ab1 and abc2's function as: abc1.xyz() and abc2.xyz().

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

You seem to be misunderstanding things. Classes introduce a separate namespace for themselves so, it is completely possible to create functions with the same name in different classes. These functions are not related in any other way other than their similar name.

Running <classname>.xyz() simply calls xyz() and prints the corresponding message.

Even if there was a relationship between the class, i.e a sub-classing relationship of the form:

class abc:
    @staticmethod
    def xyz():
        print 'class_abc'

class abc1(abc):
    @staticmethod
    def xyz():
        print 'class_abc1'

class abc2(abc1):
    @staticmethod
    def xyz():
        print 'class_abc2'

The most recent definition of xyz will override previously existing entries for it and the effect would be the same, that is abc2.xyz() would print class_abc2, abc1.xyz() prints class_abc1 and so on.

Also, do note, you're using Python 2.x but aren't actually inheriting from object. This won't create a class in the sense most people are aware with today, take a look at What is the difference between old style and new style classes in Python? to get a better idea of what this entails.

Community
  • 1
  • 1
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
0

Suppose we declare a static method with same name in different is it possible?

Yes

If it is possible then how and which function will be called.?

It's possible because classes have their own scope. Python treats each static method in your example differently. And even if your classes where related, such as in @Jim Fasarakis-Hilliard example, the current method would override the last method.

Each method will be called uniquely because each class is unrelated in your example(except for all of the classes being of type class).

Christian Dean
  • 22,138
  • 7
  • 54
  • 87