开发者

Method vs. function in case of simple function

I have original class (DownloadPage) and I need to add just one simple functionality (get_info). What is better approach in OOP?

def get_info(page):  # make simple function
    ...
result = get_info(开发者_StackOverflow社区DownloadPage())

or

class MyDownloadPage(DownloadPage):   # make new class with inheritance
    def get_info(self):               # with one method
        ...

result = MyDownloadPage().get_info()

Thanks


The answer truly depends on whether or not you want that get_info function/method can function on things other than a MyDownloadPage. At present, I'd go with the free function but when requirements solidify one way or the other it should be easy enough to transform your solution either way.

(I prefer the free function because it doesn't restrict what can be passed to it, and any functionality that relies only on another object's public interface should be a function to reduce coupling.)


Since the distance from one solution to the other is small, it hardly makes a difference with one function.

As soon as you have two functions, I'd say the derived class is more maintainable.

Once the two functions want to share a common value, like a logger or configuration variable, then you'll see more benefit.


This may be heretical, by why not just add it as a method to the existing class?

def get_info(self):
    ...

DownloadPage.get_info = get_info

I realize this isn't exactly standard practice, but I'd be curious to hear Python experts explain why not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜