0

I am getting the hang of the OOP paradigm, and the art of making expandable and reusable code is something I want to improve at. Let's say in theory that I have a Python library of utility classes that has been widely used. I want to add some convenience static methods with the same code to a particular class for ease of use, but I don't want to break my existing use of the library. What is the recommended way to implement and name the new class methods? I have a couple of guesses as follows:

1) With an overloaded method name to maintain clarity? Python's not really a good example, but in other languages such as Java? For example:

class Cat(object):
    def __init__(self, name):
        self.name = name

    def meow(self):
        meow(self.name)

    @staticmethod
    def meow(name): # <-- Granted, Python doesn't overload method names
        print "{} meowed cutely!".format(name)

2) With a different, perhaps less semantic static method name? The old name cannot be changed, so... This seems to me this could get out of hand for huge projects, with a bunch of non semantic names for just a static version of the same method. Example:

class Cat(object):
    def __init__(self, name):
        self.name = name

    def meow(self):
        meowFrom(self.name)

    @staticmethod
    def meowFrom(name): # Different, possibly less semantic name
        print "{} meowed cutely!".format(name)

I assume duplicating the code outright is a bad idea. Which is the way to go? Or is there some better design pattern? Something specific for Python I am unaware of? I want to make sure my code isn't worthless in the future; and make some personal libraries that are expansive for future projects.

4

1 回答 1

1

您可以向函数添加可选参数和关键字参数,而不会破坏它的现有用途。例如,您可以在末尾添加一个 protocol=old 参数来选择要使用的行为,在没有显式参数的情况下,旧行为是默认的。如果您想保持相同的函数名称,这是最好的选择,但如果您多次这样做,它很快就会变得笨拙。

于 2012-07-01T01:38:31.587 回答