4

Let's say I have this code:

class class1(object):
    def __init__(self):
        #don't worry about this 


    def parse(self, array):
        # do something with array

class class2(object):
    def __init__(self):
        #don't worry about this 


    def parse(self, array):
        # do something else with array

I want to be able to call class1's parse from class2 and vice-versa. I know with c++ this can be done quite easily by doing

class1::parse(array)

How would I do the equivalent in python?

1
  • 4
    This is what they call a "code smell". It looks like a bad design. What is the reason for wanting to do this? Commented Jul 22, 2010 at 19:47

1 Answer 1

5

It sounds like you want a static method:

class class1(object):
    @staticmethod
    def parse(array):
        ...

Note that in such cases you leave off the usually-required self parameter, because parse is not a function called on a particular instance of class1.

On the other hand, if you want a method which is still tied to its owner class, you can write a class method, where the first argument is actually the class object:

class class1(object):
    @classmethod
    def parse(cls, array):
        ...
Sign up to request clarification or add additional context in comments.

6 Comments

Note that if you feel the need for staticmethods like that, it's a strong indication class1 and class2 should be modules instead of classes (or at least that the parse staticmethods should be functions instead.)
@staticmethod should be avoided (and @classmethod as well if you don't need the class) in favor of making it a module-level function.
Thanks Thomas, I'm not familiar with modules, I'll have to look into that.
@Stranger: I agree with Thomas and Ignacio that typically a module-level function is preferable to a static and class method. However, static and class methods are advantageous in that you can override them in subclasses. I've done this before when designing libraries, though not very often.
Shouldn't the class method take the class (cls) as the first parameter?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.