473,714 Members | 3,438 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Simple Python class questions

A Python newbie, but some basic understanding of how classes, objects
etc work in eg VB.Net. However, I'm struggling a little to translate
this knowledge into the Python context.

I'm trying to teach myself this aspect of Python by working up a trial
project, part of which calls for pulling in data from a serial data
connection at regular intervals. It looked sensible to place all the
comms procedures/functions in their own class and module and make
calls to those functions from an object instantiated in a main
controlling module. But I'm struggling to get this working - not sure
whether it's a fundamental misunderstandin g of the use of classes in
Python, syntax errors pure and simple or, most likely, a combination
of both!

Maybe I could provide some outline code as an illustration:

Let's say I define the class in a module called comms.py. The class
isn't really going to inherit from any other class (except presumably
in the most primitive base-class sense, which is presumably automatic
and implicit in using the class keyword). Let's call the class
serial_link. So in comms.py I have:

class serial_link:
def __init__(self):
Try
Import serial # the pyserial library
Except ImportException
#Error handling

def openPort(self):
Try
#Code to try opening serial port
Return "Success"
Except SerialException
Return "Failure"

Then in my separate main calling module I might have:

Import comms
serlink=comms.s eral_link #Create instance of serial_link class
print serlink.openPor t
The last line I'm hoping would print Success or Failure. But I just
seem to get some internal reference to the openPort function enclosed
in <>.

So why doesn't it work please? I may be making multiple errors here
but as far as I can see the syntax seems right. For this particular
example, I don't need to pass any arguments from the
'seriallink.ope nPort' function so haven't included any parentheses (or
are they mandatory even if empty?) I could go on with the explanations
etc, but it may be simplest to see if anyone can spot a howler
straight out.

TIA for anyone willing to help
Jun 27 '08 #1
13 2083
Le Thursday 19 June 2008 13:54:03 John Dann, vous avez écrit*:
A Python newbie, but some basic understanding of how classes, objects
etc work in eg VB.Net. However, I'm struggling a little to translate
this knowledge into the Python context.

Maybe I could provide some outline code as an illustration:

Let's say I define the class in a module called comms.py. The class
isn't really going to inherit from any other class (except presumably
in the most primitive base-class sense, which is presumably automatic
and implicit in using the class keyword).
No it's not :) It is recommended to always use new-style classes, and thus to
give the object base explicitely :

class serial_link (object) :
...

see http://docs.python.org/ref/node33.html
print serlink.openPor t
You just forgot the (), so you're printing the method object itself without
calling it : print serlink.openPor t()

--
Cédric Lucantis
Jun 27 '08 #2
Lie
On Jun 19, 6:54*pm, John Dann <n...@prodata.c o.ukwrote:
A Python newbie, but some basic understanding of how classes, objects
etc work in eg VB.Net. However, I'm struggling a little to translate
this knowledge into the Python context.

I'm trying to teach myself this aspect of Python by working up a trial
project, part of which calls for pulling in data from a serial data
connection at regular intervals. It looked sensible to place all the
comms procedures/functions in their own class and module and make
calls to those functions from an object instantiated in a main
controlling module. But I'm struggling to get this working - not sure
whether it's a fundamental misunderstandin g of the use of classes in
Python, syntax errors pure and simple or, most likely, a combination
of both!

Maybe I could provide some outline code as an illustration:

Let's say I define the class in a module called comms.py. The class
isn't really going to inherit from any other class (except presumably
in the most primitive base-class sense, which is presumably automatic
and implicit in using the class keyword). Let's call the class
serial_link. So in comms.py I have:

class serial_link:
* * * * def __init__(self):
* * * * * * * * Try
* * * * * * * * * * * * Import serial # the pyserial library
* * * * * * * * Except ImportException
* * * * * * * * * * * * #Error handling

* * * * def openPort(self):
* * * * * * * * Try
* * * * * * * * * * * * #Code to try opening serial port
* * * * * * * * * * * * Return "Success"
* * * * * * * * Except SerialException
* * * * * * * * * * * * Return "Failure"

Then in my separate main calling module I might have:

Import comms
serlink=comms.s eral_link * * #Create instance of serial_link class
print serlink.openPor t

The last line I'm hoping would print Success or Failure. But I just
seem to get some internal reference to the openPort function enclosed
in <>.

So why doesn't it work please? I may be making multiple errors here
but as far as I can see the syntax seems right. For this particular
example, I don't need to pass any arguments from the
'seriallink.ope nPort' function so haven't included any parentheses (or
are they mandatory even if empty?) I could go on with the explanations
etc, but it may be simplest to see if anyone can spot a howler
straight out.
Yes they're mandatory even if there is no arguments, this is needed so
python can differentiate between calling function and passing function
objects.
TIA for anyone willing to help
Jun 27 '08 #3
John Dann wrote:
Let's say I define the class in a module called comms.py. The class
isn't really going to inherit from any other class (except presumably
in the most primitive base-class sense, which is presumably automatic
and implicit in using the class keyword). Let's call the class
serial_link. So in comms.py I have:

class serial_link:
def __init__(self):
Try
Import serial # the pyserial library
Stop, this can't work. Other than VB, Python actually is case sensitive, so
you must write 'try' and not 'Try' and also 'import' and not 'Import'.
Further, many (all?) statements that cause an indention are usually
terminated with a colon, so like with 'class ..:' and 'def ..:' you also
must use 'try:' and not just 'try'. Fix all these and try again, I guess
this will already help a lot.

One more thing: you are abusing exceptions. Typically, in such a short
program you only have one try-except pair in the main entry function and
all other code only throws the exceptions. In particular the __init__
function of a class should always signal errors using exceptions. However,
this is not a strict yes/no question but rather a stylistic one.
Uli

--
Sator Laser GmbH
Geschäftsführ er: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

Jun 27 '08 #4
Many thanks for the speedy replies.

On Thu, 19 Jun 2008 14:14:02 +0200, Cédric Lucantis <om**@no-log.org>
wrote:
>Le Thursday 19 June 2008 13:54:03 John Dann, vous avez écrit*:
>Let's say I define the class in a module called comms.py. The class
isn't really going to inherit from any other class (except presumably
in the most primitive base-class sense, which is presumably automatic
and implicit in using the class keyword).

No it's not :) It is recommended to always use new-style classes, and thus to
give the object base explicitely :

class serial_link (object) :
...
Can I just confirm: between the parentheses should be the literal
'object' - ie (object) - you're not just using 'object' as a
placeholder where there should be a more specific class name or
object?

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

On Thu, 19 Jun 2008 14:21:46 +0200, Ulrich Eckhardt
<ec******@sator laser.comwrote:
>Stop, this can't work. Other than VB, Python actually is case sensitive, so
you must write 'try' and not 'Try' and also 'import' and not 'Import'.
Further, many (all?) statements that cause an indention are usually
terminated with a colon, so like with 'class ..:' and 'def ..:' you also
must use 'try:' and not just 'try'. Fix all these and try again, I guess
this will already help a lot.
Sorry - the original code was syntactically correct - I just re-keyed
it rather quickly for the original newsgroup post here, rather than
copy/paste a larger chunk. I'll try to be more careful with any future
posts.
>One more thing: you are abusing exceptions. Typically, in such a short
program you only have one try-except pair in the main entry function and
all other code only throws the exceptions. In particular the __init__
function of a class should always signal errors using exceptions. However,
this is not a strict yes/no question but rather a stylistic one.
Thanks - I need to think more clearly about the best way of doing
this.

JGD
Jun 27 '08 #5
Le Thursday 19 June 2008 15:13:39 John Dann, vous avez écrit*:
Many thanks for the speedy replies.

On Thu, 19 Jun 2008 14:14:02 +0200, Cédric Lucantis <om**@no-log.org>

wrote:
Le Thursday 19 June 2008 13:54:03 John Dann, vous avez écrit*:
Let's say I define the class in a module called comms.py. The class
isn't really going to inherit from any other class (except presumably
in the most primitive base-class sense, which is presumably automatic
and implicit in using the class keyword).
No it's not :) It is recommended to always use new-style classes, and thus
to give the object base explicitely :

class serial_link (object) :
...

Can I just confirm: between the parentheses should be the literal
'object' - ie (object) - you're not just using 'object' as a
placeholder where there should be a more specific class name or
object?
Right. 'object' is a builtin python class, used as a base for all classes as
in many OO languages.

--
Cédric Lucantis
Jun 27 '08 #6
Lie
On Jun 19, 7:21*pm, Ulrich Eckhardt <eckha...@sator laser.comwrote:
John Dann wrote:
Let's say I define the class in a module called comms.py. The class
isn't really going to inherit from any other class (except presumably
in the most primitive base-class sense, which is presumably automatic
and implicit in using the class keyword). Let's call the class
serial_link. So in comms.py I have:
class serial_link:
* * def __init__(self):
* * * * Try
* * * * * * Import serial # the pyserial library

Stop, this can't work. Other than VB, Python actually is case sensitive, so
you must write 'try' and not 'Try' and also 'import' and not 'Import'.
Further, many (all?) statements that cause an indention are usually
terminated with a colon, so like with 'class ..:' and 'def ..:' you also
must use 'try:' and not just 'try'. Fix all these and try again, I guess
this will already help a lot.

One more thing: you are abusing exceptions. Typically, in such a short
program you only have one try-except pair in the main entry function and
all other code only throws the exceptions. In particular the __init__
function of a class should always signal errors using exceptions. However,
this is not a strict yes/no question but rather a stylistic one.

Uli

--
Sator Laser GmbH
Geschäftsführer : Thorsten Föcking, Amtsgericht Hamburg HR B62 932
I think it's not that hard to see that it's just a pseudo code
Jun 27 '08 #7
Lie wrote:
I think it's not that hard to see that it's just a pseudo code
"...in comms.py I have: ..." actually explicitly says that it is actual code
from a file.

*shrug*

Uli
--
Sator Laser GmbH
Geschäftsführ er: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

Jun 27 '08 #8


John Dann wrote:
>
Let's say I define the class in a module called comms.py. The class
isn't really going to inherit from any other class (except presumably
in the most primitive base-class sense, which is presumably automatic
and implicit in using the class keyword). Let's call the class
serial_link. So in comms.py I have:
If you on only ever going to have 1 serial link, you could put all
functions in the module. But the class allows for multiple links in
some future usage.
class serial_link:
Recommended for class names would be SerialLink, I believe (see PEP 8)
but at least a cap for the initial letter of python-defined classes.
def __init__(self):
Try
Import serial # the pyserial library
Except ImportException
#Error handling
The import should be at module level. You only want to do it once, not
for every link. And if the import fails, you should find out right
away. You perhaps should move try/except into the importing module. Or
re-raise the exception. Either way, the import of this module should
fail if it cannot get serial.
def openPort(self):
Try
#Code to try opening serial port
Return "Success"
Except SerialException
Return "Failure"
I would either move this to __init__ or call it from there (but the
latter only if you expect to close and reopen ports.

Then in my separate main calling module I might have:

Import comms
I guess you learned by now why cut/paste/edit-down is superior to
re-typing ;-)
serlink=comms.s eral_link
.....()

#Create instance of serial_link class
print serlink.openPor t
.....()

Terry Jan Reedy

Jun 27 '08 #9
Many thanks for the further comments:

On Thu, 19 Jun 2008 21:24:31 -0400, Terry Reedy <tj*****@udel.e du>
wrote:
> def __init__(self):
Try
Import serial # the pyserial library
>The import should be at module level. You only want to do it once, not
for every link. And if the import fails, you should find out right
away.
Yes I was wondering about that, but I wasn't clear about when 'body'
code (ie not contained within a def block) in the module might run
under Python. So it seemed to be safer to place the import statement
inside the 'constructor' to get the earliest warning of non-visibility
of pyserial. But you seem to be implying that the body code will run
when the class is instantiated - have I understood that right? It
surely doesn't run when the module containing the class is imported
into the main module - does it?? It would certainly make life easier
to place the import in the body of the module.

I think that some of the other points hinge on the this one, so let me
get my understanding straight on that first!
>
I guess you learned by now why cut/paste/edit-down is superior to
re-typing ;-)
Well I know what you mean, but actually in this instance my Python
environment is a non-networked laptop , so no easy way to cut and
paste to a networked PC! (Actually the laptop does have an Ethernet
chip in but bizarrely the driver somehow manages to kill my ADSL
connection at the exchange or ISP, which takes hours to reset so I
take care not to use this option. But learning Linux/Python is a
useful role for this otherwise defunct PC)

JGD
Jun 27 '08 #10

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

Similar topics

4
1655
by: Skip Montanaro | last post by:
(moving over from webmaster mailbox) scott> I'm sorry for bothering you, but I've tried to post to the Python scott> Tutor Mail List, tried to get someone from Bay PIggies to scott> respond, but no one is responding to my questions. If you don't scott> want to answer my questions, I'd appreciate an e-mail stating scott> that. My questions are as follows: A better place to post this would be to python-list@python.org (I've cc'd that...
1
1691
by: David Bear | last post by:
I would like some advice on what crypto lib to use. I am writing a cgi app that will store sensative data in a backend postgresql server. I have some simple numeric data I would like to make as safe as possible, without too much overhead. The goal would be to store the information in a simple reversable encrypted form. The encryption key would live only in the python app that was accessing the data. So perhaps there are two general...
30
1813
by: Brian Elmegaard | last post by:
Hi, I am struggling to understand how to really appreciate object orientation. I guess these are FAQ's but I have not been able to find the answers. Maybe my problem is that my style and understanding are influenced by matlab and fortran. I tried with the simple example below and ran into several questions: 1: Why can't I do: def __init__(self,self.x):
2
2895
by: Thierry Lam | last post by:
I'm using the WMI library for python and I was able to connect to another computer on the network with the following line: c = wmi.WMI(computer="the-network-computer", user="hello", password="hello") Is there a way to write information to a file on that computer? How do I read environment variables, for example SystemDrive?
19
1747
by: adriancico | last post by:
Hi I am working on a python app, an outliner(a window with a TreeCtrl on the left to select a document, and a RichTextBox at the right to edit the current doc). I am familiarized with OOP concepts and terms but I lack practical experience
9
1740
by: jezonthenet | last post by:
I started using Python a couple of days ago - here are a few questions: * Doesn't the __main__() method automatically execute when I run my python program? * Only when I do an import of my test.py file within python and then run test.__main__() I can see where my bugs are. Is this correct? (right now this is my only way of running my python program and see where I have problems) * Once I've done an import and then I wish to make a...
15
4572
by: Bjoern Schliessmann | last post by:
Hello all, I'm trying to simulate simple electric logic (asynchronous) circuits. By "simple" I mean that I only want to know if I have "current" or "no current" (it's quite digital) and the only elements need to be (with some level of abstraction to my specific problem) - sources (here begin currents) - ground (here end currents)
8
7982
by: Krypto | last post by:
Hi, I have used Python for a couple of projects last year and I found it extremely useful. I could write two middle size projects in 2-3 months (part time). Right now I am a bit rusty and trying to catch up again with Python. I am now appearing for Job Interviews these days and I am wondering if anybody of you appeared for a Python Interview. Can you please share the questions you were asked. That will be great help to me.
17
5813
by: Chris M. Thomasson | last post by:
I use the following technique in all of my C++ projects; here is the example code with error checking omitted for brevity: _________________________________________________________________ /* Simple Thread Object ______________________________________________________________*/ #include <pthread.h> extern "C" void* thread_entry(void*);
0
8810
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
9316
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
9078
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
9026
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
7955
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
6638
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
5959
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3160
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
2
2526
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.