开发者

What would be considered the better naming style here?

I'm writing an extension for Tkinter, and conflicted 开发者_JAVA百科on which naming style I should use for some new attributes I'm going to add.

This is the first naming style, giving all the new attributes the prefix sw_.

import Tkinter as tk

class New (tk.Button, object) :
    def __init__ (self, par) :
        tk.Button.__init__(self, par)

        attrnames = ['attr0', 'attr1', 'attr2', 'attr3']

        for name in attrnames :
            newname = 'sw_' + name
            setattr(self, newname, None)


root = tk.Tk()

new = New(root)
new.pack()

new.sw_attr0

root.mainloop()

For the second naming style I made all the new attributes attributes of the SW class. Then I made an instance of SW an attribute of my new class.

import Tkinter as tk

class SW (object) :
    def __init__ (self) :
        attrnames = ['attr0', 'attr1', 'attr2', 'attr3']

        for name in attrnames :
            setattr(self, name, None)

class New (tk.Button, object) :
    def __init__ (self, par) :
        tk.Button.__init__(self, par)

        self.sw = SW()


root = tk.Tk()

new = New(root)
new.pack()

new.sw.attr0

root.mainloop()


Python's style guide is the thing to follow - do the most readable, sensible thing. That said, it does suggest that you follow any project styles over the official Python styles, but to use Python styles when doing something new.

Python already has name-spacing as a feature of the language (with imports), so prefixes are entirely not needed.

In your situation, using prefixes is bad - it means that you break the whole duck-typing ideology of Python and the ideas of object orientation. You require the user to know that they are using attributes added by your class, not originally there, which isn't their concern. Make the class work, and avoid extra stuff that isn't important for them to know. It's just an object. They should just use it without caring about implementation.


The only recommendation is to use more informative class names, then SW. It's much more better use full words in CapCase, see pep 8.


I don't think you need any prefix.

But using a separate object will serve to confuse people who work with your code. So I have to say that a prefix is better then then introducing an extra object into the the mix.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜