Reputation: 3862
I run into a situation, where I call a static method of a class from another static method. To be sure, that I don't ask an X-Y-question, I'm trying to give some background.
I have a class, that holds a data container and several methods to convert data inside the container. As I also want the converters to be callable from the outside without a class instance, I choose static methods:
class SomeClass(object):
def __init__(self,some_data):
self.data = some_data
@staticmethod
def convert_1(data_item):
return 1+data_item
@staticmethod
def convert_2(data_item):
return 2*data_item
Now I can do SomeClass.convert_1(data_item)
without the need to create an instance of SomeClass
.
Let's say, I want to have a method inside SomeClass
, that does the two converts successively, and also want to have that method as a static method.
Can I do
@staticmethod
def combined_convert(data_item):
data_item = SomeClass.convert_1(data_item)
data_item = SomeClass.convert_2(data_item)
return data_item
inside SomeClass
? This feels wrong, as I call the class inside its own definition, but I cannot come up with another 'more pythonic' way.
Upvotes: 3
Views: 332
Reputation: 2260
You can create a class method.
@classmethod
def combined_convert(cls,data_item):
data_item = cls.convert_1(data_item)
data_item = cls.convert_2(data_item)
return data_item
Upvotes: 1