python class^module(singleton)

Both modu5 and class2 are based on a idic. Both can contain “system-wide” i.e. global variables, effectively singleton objects.

A module is like a singleton class, without constructor or inheritance.

Global variables and singletons — I figured these out because 2nd time you import a module, the module-level objects aren’t created again! You can safely construct objects at the module level and all of them become global variables. Is this similar to c++ namespace variables?

Calling a method on a class goes through __getattr__ hook. Probably no such thing in a module?

Importing a regular module actually executes the *.py file – no such feature with a class.

Modules (not classes) are hooked into the (non-trivial) import mechanism.

Module functions vs Methods have differences. All module-level methods are like classmethods, so a module can be simpler to use if you want a simple singleton class.

See also
https://learnpythonthehardway.org/book/ex40.html
http://stackoverflow.com/questions/600190/python-choosing-between-modules-and-classes

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s