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?
asked Jul 22, 2010 at 18:16
Swiss
1,3102 gold badges17 silver badges29 bronze badges
-
4This is what they call a "code smell". It looks like a bad design. What is the reason for wanting to do this?S.Lott– S.Lott2010年07月22日 19:47:21 +00:00Commented Jul 22, 2010 at 19:47
1 Answer 1
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):
...
answered Jul 22, 2010 at 18:18
Eli Courtwright
195k69 gold badges224 silver badges257 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
Thomas Wouters
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.)Ignacio Vazquez-Abrams
@staticmethod should be avoided (and @classmethod as well if you don't need the class) in favor of making it a module-level function.Swiss
Thanks Thomas, I'm not familiar with modules, I'll have to look into that.
Eli Courtwright
@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.
Niko Fohr
Shouldn't the class method take the class (cls) as the first parameter?
|
lang-py