开发者

Python and OO Programming (class attributes and derived classes)

开发者 https://www.devze.com 2023-02-06 02:25 出处:网络
I have been a Java programmer for 4,5 years. Now I\'ve switched to Python (and the main reason is that I\'m now a freelancer and I work alone). I provide source code to my costumers and sometimes I ha

I have been a Java programmer for 4,5 years. Now I've switched to Python (and the main reason is that I'm now a freelancer and I work alone). I provide source code to my costumers and sometimes I have to motivated my design choices. Now to the question. I have to support my design choice:

class Base(object):
    def foo(self):
        self.dosomethig(self.clsattr1)
        self.dosomethig(self.clsattr2)

class Derived(Base):
    clsattr1 = value1
    clsattr2 = value2

Base class is always meant to be extended or derived.

My customer (a java programmer) argues that my approach is not elegant from an OO point of view. He claims that the following approach is better:

class Base(object):
    def __init__(self, clsattr1, clsattr2):
        self.clsattr1 = clsattr1
        self.clsattr2 = clsattr2

    def foo(self):
        self.dosomethig(self.clsattr1)
        self.dosomethig(self.clsattr2)

class Derived(Base):
    def __init__(self):
        super(Derived, self).__init__(value1, value2)

I realize that second approach is much more elegant than the first one, but I told him that the first approac开发者_如何学Goh is much more handy. I told him I do not see any issue, but he is not convinced. Is the first approach so bad? And why?


There does not seem to be any difference whatsoever. Don't waste your time arguing with him -- it might be quicker to just refactor your classes and take the money.


If the Base class requires the values to do its thing, then it should be explicit.

In other programming languages the requirement could be set with abstract methods, one for each value, but that's not in the Python style, and simulating it would be cumbersome.

The most interesting difference between the examples is that the first code fragment tries to use class variables of the Base class, which would impact every derived class and all its instances. Which way should it be? Values per hierarchy? Per derived class? Per instance?

In the best pythonic style, if objects can set their own initialization values, then the Base class should use reasonable defaults for them, and provide a mechanism for subclasses and their instances to override them.

class Base(object):
    def __init__(self, attr1=DEFAULT1, attr2=DEFAULT2):
        self.attr1 = attr1
        self.attr2 = attr2


The second snippet could only be called 'elegant' when compared with Java. Not only it's almost twice as long, the use of '__' variables is a clear sign that the programmer is fighting against the language, and there are a lot of possible errors.

If you (or your client) wants Java, you know where to find it.

0

精彩评论

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

关注公众号