473,399 Members | 4,177 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Python Class use


Hello,

I am running Python on Mac OS X. The interpreter has been great for
learning the basics, but I would now like to be able to reuse code.
How do I write reusable code? I have done it "The Java way": write
the class, and save it to my home directory, then call it from the
interpreter, here is an example.

########my saved file######
class MyClass:
def f(self):
return 'calling f from MyClass'

#######interpreter#########
x = MyClass()
(unhelpful error mesages)


I hope I have clearly explained my problem. Because I
don't know the solution top this, I have to rewrite my methods
in the interpreter every single time I need to change something, and
I am quite certain that that is not the best way to do it.

Thank you very much.

S

Feb 7 '06 #1
5 1324
S Borg <sp********@gmail.com> wrote:
I am running Python on Mac OS X. The interpreter has been great for
learning the basics, but I would now like to be able to reuse code.
Excellent. Code reuse is what it's all about!
How do I write reusable code? I have done it "The Java way": write
the class, and save it to my home directory, then call it from the
interpreter


That's pretty much what you do in Python. Write your class into a
file called foo.py and save it. Then, start up an interpreter and do
"import foo". You might want to read about "modules" in the Python
tutorial (http://docs.python.org/tut/node8.html).
Feb 7 '06 #2
Huh? You definitely must import that module. Then, is your homedir
listed in sys.path?

Greetings,
F. Sidler
Feb 7 '06 #3
S Borg schreef:
Hello,

I am running Python on Mac OS X. The interpreter has been great for
learning the basics, but I would now like to be able to reuse code.
How do I write reusable code? I have done it "The Java way": write
the class, and save it to my home directory, then call it from the
interpreter, here is an example.

########my saved file######
class MyClass:
def f(self):
return 'calling f from MyClass'

#######interpreter#########
x = MyClass()
(unhelpful error mesages)


I hope I have clearly explained my problem.


I think so.

Python does this different from Java. One difference is that Python
allows you to put more than one class in a module (you also don't have
to put everything in a class; code can live in a module's global
namespace too). Then, to use code from that module, you have to import
it with the import statement.

Putting it all together, you could create a file MyModule.py which
contains the code you mentioned, and then use it like this:

import MyModule

x = MyModule.MyClass()
x.f()

Or you could directly import MyClass into the global namespace like this:

from MyModule import MyClass

x = MyClass()
x.f()

But that's not recommended since it clutters the global namespace and
makes it more difficult to see which name comes from which module.
--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton

Roel Schroeven
Feb 7 '06 #4
Roel Schroeven wrote:
import MyModule

x = MyModule.MyClass()
x.f()

Or you could directly import MyClass into the global namespace like this:

from MyModule import MyClass

x = MyClass()
x.f()

But that's not recommended since it clutters the global namespace and
makes it more difficult to see which name comes from which module.


No, no, it's completely kosher to use "from module import Class".
It won't clutter the namespace any more than the above as long
as you just import one class, and there's no "magically" appearing
names in any namespace. You should avoid "from module import *" in
your programs though, but feel free to use it in the interpreter.

Just using "from MyModule import *" and then simply using "MyClass"
in the code is confusing for others who read your code, since it's
not appearent where MyClass came from. As your progam grows and you
use more modules, it will get worse. Imagine that you have three
modules and do:

from module1 import *
from module2 import *
from module3 import *

How on earth will someone reading that progam know where to find the
definition of a class or function then, and what will happen if you
happened to use the same class or function name in more than one
module? As software grows, it gets more and more important to prevent
such problems.

With either "from module1 import Class1, Class2" or "import module1"
follwed by "o = module1.Class1()" etc, it will always be clear from
the source code file where Class1 is used, where it's defined. The
"from ... import ..." style means that you need to find the import
statement to figure out where it's from, so the plain "import x"
might be preferable, but that's a judgement call you need to make
from case to case.

But more importantly, I think "S" should realize that while the
interpreter is nice as a calculator etc and for experiments, the
normal way to use Python is to put practically all your code in
files. It's common to write code so that it's both useful as a
module and a stand alone program. You achieve by looking at the
"magic" __name__ variable, which is set to "__main__" if a script
is used as direct input to python, and to the file name (sans .py)
if imported.

E.g. if you have a file "whoami.py" containing just "print __name__",
doing "python whoami.py" will print out "__main__", but doing an
"import whoami" from the interpreter would print out "whoami".

So, if you want some code to check how many files and/or directories
you have in your current directory, you could make a module like this:

filecount.py---------------

import os

def filecount():
return len(os.listdir('.'))

if __name__=='__main__':
print "There are", filecount(), "entries in the current directory"

---------------------------

Then, "python filecount.py" might display

There are 12 entries in the current directory

while an interactive session might give:
import filecount
print filecount.filecount() 12

Feb 8 '06 #5
S Borg wrote:
Hello,

I am running Python on Mac OS X. The interpreter has been great for
learning the basics, but I would now like to be able to reuse code.
How do I write reusable code? I have done it "The Java way": write
the class, and save it to my home directory, then call it from the
interpreter, here is an example.

########my saved file######
class MyClass:
def f(self):
return 'calling f from MyClass'

#######interpreter#########
x = MyClass()
(unhelpful error mesages)


This message - that is called a 'traceback' - may seem unhelpful to you,
but as a general rule, please post it : it may be *very* helpful to
those trying to help you (well, in this case the problem is pretty
obvious, but most of the time it is not...)

NB: see other answers in this thread about your actual problem - and
please take time to read the Fine Manual, specially:
http://docs.python.org/tut/node8.html
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Feb 8 '06 #6

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

Similar topics

220
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have...
54
by: Brandon J. Van Every | last post by:
I'm realizing I didn't frame my question well. What's ***TOTALLY COMPELLING*** about Ruby over Python? What makes you jump up in your chair and scream "Wow! Ruby has *that*? That is SO...
49
by: Ville Vainio | last post by:
I don't know if you have seen this before, but here goes: http://text.userlinux.com/white_paper.html There is a jab at Python, though, mentioning that Ruby is more "refined". -- Ville...
7
by: svilen | last post by:
hello again. i'm now into using python instead of another language(s) for describing structures of data, including names, structure, type-checks, conversions, value-validations, metadata etc....
1
by: M.E.Farmer | last post by:
Hello c.l.py!, I have just finished this and decided to share. PySourceColor is a module to convert Python source into colored html. Yes it has been done before, but I like this better:) You can...
270
by: Jordan | last post by:
Hi everyone, I'm a big Python fan who used to be involved semi regularly in comp.lang.python (lots of lurking, occasional posting) but kind of trailed off a bit. I just wrote a frustration...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...
0
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,...
0
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...

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.