473,625 Members | 2,733 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to organise classes and modules

Hi, this is my first mail to the list so please correct me if Ive done
anything wrong.

What Im trying to figure out is a good way to organise my code. One
class per .py file is a system I like, keeps stuff apart. If I do
that, I usually name the .py file to the same as the class in it.

File: Foo.py
*************** ********
class Foo:
def __init__(self):
pass
def bar(self):
print 'hello world'

*************** *********

Now, in my other module, I want to include this class. I tried these two ways:
import Foo
Foo.Foo.bar() Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as
first argument (got nothing instead)

Some unbound method error. Have I missunderstood something or am I on
the right track here?

I did this to, almost the same thing:
from Foo import Foo
Foo.bar() Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as
first argument (got nothing instead)

One thing that I tried that worked ok was this:
import Foo
instance=Foo.Fo o()
instance.bar() hello world

But in my opinion, this is very ugly. Especially if the class names
are long, like my module/class TileDataBaseMan ager. But is this the
"right" way in python?

Another (ugly) way that Ive considered is the following. Break it out
of the class, save the functions in a file alone, import the file and
treat it like a class:

File: Foo2.py
*************** ********
def bar(self):
print 'hello world'

*************** *********
import Foo2
Foo2.bar()

hello world

Very clean from the outside. I would like something like this. But,
here, I loose the __init__ function. I have to call it manually that
is, which s not good. Also, maybe the biggest drawback, its no longer
in a class. Maybe its not that important in python but from what Ive
learned (in c++) object orientation is something to strive for.

So, to sum it up, I have one class in one file, both with the same
name. How do I store/import/handle it in a nice, clean and python-like
manner?

Thank you very much in advance.
/ Alex
May 15 '06 #1
5 1650

On 2006-05-15, Alex <mi******@gmail .com> wrote:
import Foo
Foo.Foo.bar() Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as
first argument (got nothing instead)

...

One thing that I tried that worked ok was this:
import Foo
instance=Foo.Fo o()
instance.bar()

hello world

But in my opinion, this is very ugly. Especially if the class names


Are you sure you understand object-oriented programming? Reading the
Python tutorial[1] and re-reading the above error messages should clue
you in to what you're doing wrong. To put it simply, the whole point of
classes is that you create instances of them, each having their own
internal state, and then invoke their methods to accomplish whatever it
is that you want your program to accomplish.

1. http://docs.python.org/tut/
--
Ilkka Poutanen [http://ipo.iki.fi/]
And unto this, Conan;
May 15 '06 #2
Alex wrote:
Hi, this is my first mail to the list so please correct me if Ive done
anything wrong.

What Im trying to figure out is a good way to organise my code. One
class per .py file is a system I like, keeps stuff apart. If I do
that, I usually name the .py file to the same as the class in it.
First point is that Python doesn't force you to put everything in
classes - if you just need a function, well, make it a function !-)

Also, the common pattern is to put closely related
classes/functions/constants in a same module, and closely related
modules in the same package. Since Python uses a "one file == one
module" scheme, the Javaish "one class per file" idiom leads to overly
complicated imports. And the most common naming scheme for modules is
'alllowercase'.
File: Foo.py
*************** ********
class Foo:
def __init__(self):
pass
def bar(self):
print 'hello world'

*************** *********

Now, in my other module, I want to include this class. I tried these two
ways:
import Foo
Foo.Foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as
first argument (got nothing instead)

Some unbound method error. Have I missunderstood something
Yes:
1/ you usually need to instanciate the class to call an instance method
1/ in this case, bar doesn't need to be a method, since it doesn't
depend on the instance it's called on - a plain old function would be a
better fit.
or am I on
the right track here?

I did this to, almost the same thing:
from Foo import Foo
Foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as
first argument (got nothing instead)

One thing that I tried that worked ok was this:
import Foo
instance=Foo.Fo o()
instance.bar()
hello world

But in my opinion, this is very ugly.
Nope, it's just OO at work.
Especially if the class names
are long, like my module/class TileDataBaseMan ager. But is this the
"right" way in python?
If you want to import a class from a module and create an instance of
that class, yes.
Another (ugly) way that Ive considered is the following. Break it out
of the class,
Which would be a sensible thing to do given the current implementation
of bar().
save the functions in a file alone,
Nothing prevent you from putting many functions in a same module, you
know...
import the file
s/file/module/
and
treat it like a class:
???
File: Foo2.py
*************** ********
def bar(self):
print 'hello world'

*************** *********
import Foo2
Foo2.bar()

hello world


You don't "treat it like a class", you're just using the normal
namespace resolution mechanism. Modules are namespaces, classes are
namespaces, objects (class instances) are namespaces, and the dot is the
lookup operator (ie : somenamespacena me.somename means 'retrieve what's
actually bound to name 'somename' in namespace 'somenamespacen ame').
Very clean from the outside. I would like something like this. But,
here, I loose the __init__ function.
Which in the given implementation is just doing nothing.

Ok, I understand that this is just example code. The rule here is:
- if you need per-instance state management, use a class (that you of
course need to instanciate - else you can't have per-instance state !-)
- if you don't need per-instance state management, use a plain function.
I have to call it manually that
is, which s not good. Also, maybe the biggest drawback, its no longer
in a class.
def MyFunc():
pass

print MyFunc.__class_ _.__name__

Python function's are instances of the function class.
Maybe its not that important in python but from what Ive
learned (in c++) object orientation is something to strive for.
print "object orientation".fi nd("class")

Being OO doesn't mean using classes. <troll>And FWIW, there quite enough
procedural Java code around to prove that using classes doesn't mean
doing OO !-) </troll>
So, to sum it up, I have one class in one file, both with the same
name. How do I store/import/handle it in a nice, clean and python-like
manner?


Quit the Javaish "one-class-per-file" idiom, don't bother using classes
when plain old function will do, and you'll be on track...

FWIW, Python's standard lib is open-source, so why not have a look at
the source code to see how it is organized ?

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
May 15 '06 #3
> Some unbound method error. Have I missunderstood something or am I on
the right track here?
You misunderstood that you'd have to create an instance first before
invoking a method on that very instance. That is the same in C++, btw.
But in my opinion, this is very ugly. Especially if the class names
are long, like my module/class TileDataBaseMan ager. But is this the
"right" way in python?
I'm not sure what you mean by ugly. If you mean by ugly that you have to
instantiate an object before using it - that is the way it works in _all_
OO languages.

If you mean that you find it ugly to have long modulenames that are the same
as the class-name - yes it is ugly - but that is utterly your personal
decision to do so. In python, modules usually contain several classes, and
the module name groups them by function and has a name related to that
function. So most of the times one writes

import module

o = module.Class()

Which is not ugly - IMHO at least :) Especially not more ugly than using C++
namespaces, isn't it? And that is what a module essentially is: a
namespace.

Very clean from the outside. I would like something like this. But,
here, I loose the __init__ function. I have to call it manually that
is, which s not good. Also, maybe the biggest drawback, its no longer
in a class. Maybe its not that important in python but from what Ive
learned (in c++) object orientation is something to strive for.
You seem to have some troubles with OO in general and with the way python
does it. So I think it is kind of funny if you claim it is something to
strive for. OO is no silver bullet - if you have something that can be
dealt with using a function, it's perfectly good design to use one. Having
objects just for the sake of it introduces all sorts of problems, related
to unnecessary state, unclear implementation smeared over several methods
an the like.
So, to sum it up, I have one class in one file, both with the same
name. How do I store/import/handle it in a nice, clean and python-like
manner?


Group classes that belong to the same domain in one module. Import that,
possibly using an alias like

import MyLongDescripti veModuleName as mn

don't fall for the temptation to use

from MyLongDescripti veModuleName import *

as it will cause only more headache!

Diez
May 15 '06 #4
On 5/15/06, bruno at modulix <on***@xiludom. gro> wrote:
Alex wrote:
Hi, this is my first mail to the list so please correct me if Ive done
anything wrong.

What Im trying to figure out is a good way to organise my code. One
class per .py file is a system I like, keeps stuff apart. If I do
that, I usually name the .py file to the same as the class in it.


First point is that Python doesn't force you to put everything in
classes - if you just need a function, well, make it a function !-)

Also, the common pattern is to put closely related
classes/functions/constants in a same module, and closely related
modules in the same package. Since Python uses a "one file == one
module" scheme, the Javaish "one class per file" idiom leads to overly
complicated imports. And the most common naming scheme for modules is
'alllowercase'.
File: Foo.py
*************** ********
class Foo:
def __init__(self):
pass
def bar(self):
print 'hello world'

*************** *********

Now, in my other module, I want to include this class. I tried these two
ways:
> import Foo
> Foo.Foo.bar()


Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as
first argument (got nothing instead)

Some unbound method error. Have I missunderstood something


Yes:
1/ you usually need to instanciate the class to call an instance method
1/ in this case, bar doesn't need to be a method, since it doesn't
depend on the instance it's called on - a plain old function would be a
better fit.
or am I on
the right track here?

I did this to, almost the same thing:
> from Foo import Foo
> Foo.bar()


Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as
first argument (got nothing instead)

One thing that I tried that worked ok was this:
> import Foo
> instance=Foo.Fo o()
> instance.bar()


hello world

But in my opinion, this is very ugly.


Nope, it's just OO at work.
Especially if the class names
are long, like my module/class TileDataBaseMan ager. But is this the
"right" way in python?


If you want to import a class from a module and create an instance of
that class, yes.
Another (ugly) way that Ive considered is the following. Break it out
of the class,


Which would be a sensible thing to do given the current implementation
of bar().
save the functions in a file alone,


Nothing prevent you from putting many functions in a same module, you
know...
import the file


s/file/module/
and
treat it like a class:


???
File: Foo2.py
*************** ********
def bar(self):
print 'hello world'

*************** *********
> import Foo2
> Foo2.bar()


hello world


You don't "treat it like a class", you're just using the normal
namespace resolution mechanism. Modules are namespaces, classes are
namespaces, objects (class instances) are namespaces, and the dot is the
lookup operator (ie : somenamespacena me.somename means 'retrieve what's
actually bound to name 'somename' in namespace 'somenamespacen ame').
Very clean from the outside. I would like something like this. But,
here, I loose the __init__ function.


Which in the given implementation is just doing nothing.

Ok, I understand that this is just example code. The rule here is:
- if you need per-instance state management, use a class (that you of
course need to instanciate - else you can't have per-instance state !-)
- if you don't need per-instance state management, use a plain function.
I have to call it manually that
is, which s not good. Also, maybe the biggest drawback, its no longer
in a class.


def MyFunc():
pass

print MyFunc.__class_ _.__name__

Python function's are instances of the function class.
Maybe its not that important in python but from what Ive
learned (in c++) object orientation is something to strive for.


print "object orientation".fi nd("class")

Being OO doesn't mean using classes. <troll>And FWIW, there quite enough
procedural Java code around to prove that using classes doesn't mean
doing OO !-) </troll>
So, to sum it up, I have one class in one file, both with the same
name. How do I store/import/handle it in a nice, clean and python-like
manner?


Quit the Javaish "one-class-per-file" idiom, don't bother using classes
when plain old function will do, and you'll be on track...

FWIW, Python's standard lib is open-source, so why not have a look at
the source code to see how it is organized ?

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'on***@xiludom. gro'.split('@')])"
--
http://mail.python.org/mailman/listinfo/python-list


Thanks for taking your time to help me out. :) You have cleared out
many of my doubts. BTW, should I post "thank you" stuff here or does
it just clutter? I tried sending an email to your personal email
listed (the one from which you send that mail to the list), but I got
this error:

PERM_FAILURE: DNS Error: Domain name not found

So I guess the entire list will have to be thanked for the help. :)
May 15 '06 #5
Alex wrote:
On 5/15/06, bruno at modulix <on***@xiludom. gro> wrote:
(snip)
Thanks for taking your time to help me out. :) You have cleared out
many of my doubts. BTW, should I post "thank you" stuff here
Ain't that what you just did ?-)
or does
it just clutter?
Nope, 'thank you' are always welcomes - eventually, take time to snip
irrelevant material (no use to repost 100+ lines just to add 'thank you'
at the bottom).
I tried sending an email to your personal email
listed (the one from which you send that mail to the list), but I got
this error:

PERM_FAILURE: DNS Error: Domain name not found
hint : have a look at my signature.
So I guess the entire list will have to be thanked for the help. :
)


indeed.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'on***@xiludom. gro'.split('@')])"
May 15 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1579
by: Brad Tilley | last post by:
I don't understand classes very well... maybe some day. Is it just me or are they supposed to be difficult to understand? They make my head hurt. Anyway, because I don't understand classes well, I avoid using them. However, many modules in the standard library are implemented as classes: sgmllib, HTMLParser, etc. Is it possible to use these modules without getting into OO programming and inheritance and all the other lofty, theoretical...
8
1638
by: Rob Snyder | last post by:
Greetings - I have a situation where I need to be able to have a Python function that will take all the modules in a given directory and find all the classes defined in these modules by name. Ultimately, I would need to loop through all of these, instantiating each of the classes in turn and calling a pre-known method of each. Finding the name of each module is not a problem, but loading the classes out the module once I know the name...
3
2559
by: Javi | last post by:
I have some doubts about what is the best method to distribute classes in .cpp and .h files: - Should I use a file per class? or should I group similar classes in one file? - Is it good to put a lot of class declarations in the same .h, and their definitions in different .cpps? - And, to the contrary, many definitions in one cpp and declarations in different .h? - How to deal with precompiled headers? is it ok to include all headers in the...
5
2364
by: M Shafaat | last post by:
Hi, I want to develop a number of generic components which I intend to use in different applications. Is it a good idea to put all these generic components in one and the same namespace, e.g. named GenApplCtrls, without any regard to whether or not the components have any functionality in common? Which principles should be considered when deciding which classes to belong to a namespace?
8
31873
by: JackRazz | last post by:
Is it possible to create a static class in vb.net like c# does? I want the code to create a single global instance of a class that is inherited from another class. I could use a module, but I can't inherit from a class with it. How would 'public static class classname' be different from just creating a class with all the properties being static? Thanks - JackRazz
11
1470
by: John Salerno | last post by:
From my brief experience with C#, I learned that it was pretty standard practice to put each class in a separate file. I assume this is a benefit of a compiled language that the files can then be grouped together. What I'm wondering is how is this normally handled in Python? Is it normal for classes to be put in separate modules? It seems like this can get out of hand, since modules are separate from one another and not compiled...
173
5658
by: Zytan | last post by:
I've read the docs on this, but one thing was left unclear. It seems as though a Module does not have to be fully qualified. Is this the case? I have source that apparently shows this. Are modules left-over from VB6, and not much used anymore? It seems that it is better to require Imports or use fully qualified names for functions in other classes/modules, but a Module doesn't require this, cluttering the global namespace. It seems...
12
2081
by: Janaka Perera | last post by:
Hi All, We have done a object oriented design for a system which will create a class multiply inherited by around 1000 small and medium sized classes. I would be greatful if you can help me with the following: Can this create any problems with GNU g++ compilation, linking etc? What would be the impact to the performance of the system? Anything else we have to consider?
5
1550
by: jyck91 | last post by:
Can anyone give me some ideas to organise a composition analyzer in C? It analyses an english composition. What functions should it include? eg. frequency of letter/ words thanks for help
0
8253
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8692
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8354
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8497
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7182
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6116
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4089
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4192
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2621
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.