开发者

organising classes and modules in python

I'm getting a bit of a headache trying to figure out how to organise modules and classes together. Coming from C++, I'm used to classes encapsulating all the data and methods required to process that data. In python there are modules however and f开发者_JAVA技巧rom code I have looked at, some people have a lot of loose functions stored in modules, whereas others almost always bind their functions to classes as methods.

For example say I have a data structure and would like to write it to disk.

One way would be to implement a save method for that object so that I could just type

MyObject.save(filename)

or something like that. Another method I have seen in equal proportion is to have something like

from myutils import readwrite

readwrite.save(MyObject,filename)

This is a small example, and I'm not sure how python specific this problem is at all, but my general question is what is the best pythonic practice in terms of functions vs methods organisation?


It seems like loose functions bother you. This is the python way. It makes sense because a module in python is really just an object on the same footing as any other object. It does have language level support for loading it from a file but other than that, it's just an object.

so if I have a module foo.py:

import pprint

def show(obj):
    pprint(obj)

Then the when I import it from bar.py

import foo

class fubar(object):
   #code

   def method(self, obj):
       #more stuff
       foo.show(obj)

I am essentially accessing a method on the foo object. The data attributes of the foo module are just the globals that are defined in foo. A module is the language level implementation of a singleton without the need to prepend self to every methods argument list.

I try to write as many module level functions as possible. If some function will only work with an instance of a particular class, I will make it a method on the class. Otherwise, I try to make it work on instances of every class that is defined in the module for which it would make sense.

The rational behind the exact example that you gave is that if each class has a save method, then if you later change how you are saving data (from say filesystem to database or remote XML file) then you have to change every class. If each class implements an interface to yield that data that it wants saved, then you can write one function to save instances of every class and only change that function once. This is known as the Single Responsibility Principle: Each class should have only one reason to change.


If you have a regular old class you want to save to disk, I would just make it an instance method. If it were a serialization library that could handle different types of objects I would do the second way.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜