[Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)

P

Peter Otten

Thanks to all your answers, I have read a lot about namespaces, but still
there's something I do not understood. I have tried your example but as I
expected:

line 13, in HandoverSQLCursor
curs.execute("SELECT * FROM lager")
AttributeError: 'builtin_function_or_method' object has no attribute
'execute'

You have assigned a built-in function to the curs variable. Example:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute
'execute'

You can find out the name of the actual function with
open

PS: This question is only loosely related to your previous question. You
should have started a new thread.
 
R

Roy Smith

Thanks to all your answers, I have read a lot about namespaces, but still
there's something I do not understood. I have tried your example but as I
expected:

line 13, in HandoverSQLCursor
curs.execute("SELECT * FROM lager")
AttributeError: 'builtin_function_or_method' object has no attribute
'execute'

I will try my best to write tomorrow a sample as detailed as possible.

Good evening

Polishing up my crystal ball, I'm going to guess you're using one of the
Python Database APIs (http://www.python.org/dev/peps/pep-0249/). And
that at some point, you tried to generate a cursor by doing:

curs = connection.cursor

instead of

curs = connection.cursor()

This left you with curs being (a reference to) the cursor function
itself, rather than what the function returns when it's called.

You own the oracle 20 minutes spent reading ESR's classic essay, "How To
Ask Questions The Smart Way" (http://tinyurl.com/cabqnop).
 
P

prilisauer

Okay, I try to publish this sample, and yes it's not a working piece of code, but I try to "draw" my problem that way. As you will see, I load modules, create cursor,... in the main.py. In the lower section you see, that the modules should execute sqls. In case It could occur that two queries occur at the same time. PS: IT IS NOT A QUESTION ABOUT SQL, etc. I do not understand, how I could handle the part which is marked with Problemsection1 and Problemsection2

I hope really found the right "wording". thank to all your help.


main.py
import HomeLog # LogHandler
import HomeSocketServer # Threaded TCP Socket Server
import HomeDatastore # SQLite DB
import HomeDaliServer # Connects to USB Device
import HomeScheduler # Advanced scheduler functions


# Attach Loghandler
Loghandler = HomeLog.Logging()
# Attach SocketServer
HomeSocketServer.HomeSocketServerStart()

# Attach Scheduler
HomeSched = HomeScheduler.HomeScheduler()
HomeSched.SchedulerStart()
HomeSched.SchedulerJobs()

# Attach Datastore
Datastore=HomeDatastore.HomeDBStore()
Datastore=Datastore.Startup()

#Attach Dali Driver
Dali=HomeDaliServer.Startup()
# This is a "Sample" that builds 2byte Cmd and transmits it on bus
PowerOnLamp1=Dali.send(0,0,1,80)

###############################################################
HomeDaliServer.py
.........
def send (self,DaliAdress,RequestType,Request,RequestValue):
# Problemsection1:
# Here it's getting Interesting
# We're at the HomeDaliServer, and now I want to use QuerySqlite() in the file HomeDatastore.py

###############################################################
HomeScheduler.py
# Problemsection2:
# If new workerthread is started, Informations must be queried using QuerySlite() and also update data


###############################################################
HomeDatastore.py
def QuerySqlite():
#doing something here..
# returning Data

###############################################################
 
T

Terry Reedy

By the way, I think I have found the correct "wording". for my
understood, the "handover" of objects to imported modules doesn't
work because, e.g. trying to hand-over an SQLite connection into a
imported module, can't work because the "attributes" are not
transfered.

I have not followed this thread, and do not know the context of your
statement, or the code that did not work, but if you hand a Python
object to an imported module, and something within the module can access
the object, then all of its attributes are also accessible, the same as
from the original module.
 
D

Dennis Lee Bieber

Okay, I try to publish this sample, and yes it's not a working piece of code, but I try to "draw" my problem that way. As you will see, I load modules, create cursor,... in the main.py. In the lower section you see, that the modules should execute sqls. In case It could occur that two queries occur at the same time. PS: IT IS NOT A QUESTION ABOUT SQL, etc. I do not understand, how I could handle the part which is marked with Problemsection1 and Problemsection2
#Attach Dali Driver
Dali=HomeDaliServer.Startup()
# This is a "Sample" that builds 2byte Cmd and transmits it on bus
PowerOnLamp1=Dali.send(0,0,1,80)

###############################################################
HomeDaliServer.py
........
def send (self,DaliAdress,RequestType,Request,RequestValue):

You've left out all the important stuff...

Python uses indentation to delimit code... The above is fully to the
left, which implies it is a MODULE level function, NOT a method in a
CLASS.

You also do not show us the "Startup()" code, so we can't tell if
that is a class or not.

You do not include a traceback of the error...
 
T

Thomas Bach

Hi there,

[…] In the lower section you see, that the modules should execute
sqls. In case It could occur that two queries occur at the same
time. PS: IT IS NOT A QUESTION ABOUT SQL, etc. I do not understand,
how I could handle the part which is marked with Problemsection1 and
Problemsection2

I actually do not understand the problem you are stating. But, did you
have a look at SQLAlchemy? If you are coping a lot with SQL it really
makes your life much easier and they also provide the necessary
mechanisms for threading.
import HomeLog # LogHandler

Modules should be written all lower-case separated by underscores.
# Attach Loghandler
Loghandler = HomeLog.Logging()

Have a look at the logging module and tutorial. I don't know what is
in HomeLog.Logging, but this doesn't seem right.

Variables defined at module level should be written all upper-case.
# Attach SocketServer
HomeSocketServer.HomeSocketServerStart()

# Attach Scheduler
HomeSched = HomeScheduler.HomeScheduler()
[…]
# This is a "Sample" that builds 2byte Cmd and transmits it on bus
PowerOnLamp1=Dali.send(0,0,1,80)

You do all this on the module level? These things should go into
functions with proper names or at least into a

if __name__ == '__main__':
pass

###############################################################
HomeDaliServer.py
........
def send (self,DaliAdress,RequestType,Request,RequestValue):
# Problemsection1:
# Here it's getting Interesting
# We're at the HomeDaliServer, and now I want to use QuerySqlite()
in the file HomeDatastore.py

So, where's the problem?

# make sure not to introduce cyclic dependence here!
import home_data_store

def send (connection,DaliAdress,RequestType,Request,RequestValue):
results = home_data_store.query_sqlite(connection, …)
return results

###############################################################
HomeScheduler.py
# Problemsection2:
# If new workerthread is started, Informations must be queried using
QuerySlite() and also update data

So, here's a first sketch (untested):

def query():
data = do_something()
return data

def update(data):
do_something_with(data)

HomeDatastore.py
def QuerySqlite():
#doing something here..
# returning Data

Have you read the Python tutorial by the way?

Regards,
Thomas.
 
D

Dave Angel

Okay, I try to publish this sample, and yes it's not a working piece of code, but I try to "draw" my problem that way. As you will see, I load modules, create cursor,... in the main.py. In the lower section you see, that the modules should execute sqls. In case It could occur that two queries occur at the same time. PS: IT IS NOT A QUESTION ABOUT SQL, etc. I do not understand, how I could handle the part which is marked with Problemsection1 and Problemsection2
You're miles from being ready to worry about "the same time." Don't
start threading till you can get a simple multi-module program understood.
I hope really found the right "wording". thank to all your help.


main.py

For some reason you capitalize all those filenames, so you're stuck with
unpythonic module names. If you want your code readable, use lowercase
for module name, and Capitalized for class name.
import HomeLog # LogHandler
import HomeSocketServer # Threaded TCP Socket Server
import HomeDatastore # SQLite DB
import HomeDaliServer # Connects to USB Device
import HomeScheduler # Advanced scheduler functions


# Attach Loghandler
Loghandler = HomeLog.Logging()
# Attach SocketServer
HomeSocketServer.HomeSocketServerStart()

# Attach Scheduler
HomeSched = HomeScheduler.HomeScheduler()
HomeSched.SchedulerStart()
HomeSched.SchedulerJobs()

# Attach Datastore
Datastore=HomeDatastore.HomeDBStore()
Datastore=Datastore.Startup()

#Attach Dali Driver
Dali=HomeDaliServer.Startup()
# This is a "Sample" that builds 2byte Cmd and transmits it on bus
PowerOnLamp1=Dali.send(0,0,1,80)

###############################################################
HomeDaliServer.py import HomeDatastore
........
def send (self,DaliAdress,RequestType,Request,RequestValue):
Nobody's going to be able to understand your code if you persist in
using self in unpythonic ways. It's used as the first argument of a
class method. Period.
# Problemsection1:
# Here it's getting Interesting
# We're at the HomeDaliServer, and now I want to use QuerySqlite() in the file HomeDatastore.py
So call it:
firstarg = whatever * RequestType
secondarg = something different + RequestValue
result = HomeDatastore.QuerySqlite(firstarg, secondarg)
###############################################################
HomeScheduler.py
Where are your import statements? No module automatically sees imports
that were done elsewhere. Import what you need in a module.
# Problemsection2:
# If new workerthread is started, Informations must be queried using QuerySlite() and also update data
I don't see any 'update data' function anywhere, but if you want to call
QuerySqlite, you need to call it:
thisresult = HomeDatastore.QuerySqlite(him, her, theother)
###############################################################
HomeDatastore.py
def QuerySqlite():
You presumably mean
def QuerySqlite(firstparam, secondparam):

since a function with no arguments is going to be stuck trying to use
globals, and that's not a good habit to get into.
#doing something here..
#doing something with those parameters, and only those parameters
 
P

prilisauer

Hello Dave,

Thank you, for your help, I'll try my best.

To all others, PLEASE be pleasant with my nescience, I'll tried to describe not a specific error at my Program. I'll tried to get rid of that missing link this sample is only theoretic, but the code really exists and is over 1000 lines long.

I understood how to transmit data to a class, but I do not understood how that class could access an SQL object, that is allready opened at a other class without getting into troubles with sqlite.

For my understood, the newsgroup isn't a place only to solve concrete problems. I think you're not only a "helpdesk" :), If I'm at the wrong group to get some Ideas how to solve my "issues"


Ps.: DaveA I don't know how to say it, but I treasure your great work here, giving such detailed good answers.

PPs.: I know, that my codingstyle isn't that great, I've haven't programmed the last two years. You're welcome to guess what I've worked 8 years long. :) you will laugh till you fall of your keyboard :p

PPPs.: I' will use that day to check out the PEP's and correct my coding style, and naming.
 
P

prilisauer

Hello Dave,

Thank you, for your help, I'll try my best.

To all others, PLEASE be pleasant with my nescience, I'll tried to describe not a specific error at my Program. I'll tried to get rid of that missing link this sample is only theoretic, but the code really exists and is over 1000 lines long.

I understood how to transmit data to a class, but I do not understood how that class could access an SQL object, that is allready opened at a other class without getting into troubles with sqlite.

For my understood, the newsgroup isn't a place only to solve concrete problems. I think you're not only a "helpdesk" :), If I'm at the wrong group to get some Ideas how to solve my "issues"


Ps.: DaveA I don't know how to say it, but I treasure your great work here, giving such detailed good answers.

PPs.: I know, that my codingstyle isn't that great, I've haven't programmed the last two years. You're welcome to guess what I've worked 8 years long. :) you will laugh till you fall of your keyboard :p

PPPs.: I' will use that day to check out the PEP's and correct my coding style, and naming.
 
C

Cameron Simpson

| To all others, PLEASE be pleasant with my nescience, I'll tried to
| describe not a specific error at my Program.

If you don't describe specific errors, you won't get specific advice.

If you're after stylistic and technique advice, please offer real,
specific, _running_ code and say "I'm doing this X way, should I?"
or something like that.

People here like specific questions. Even theoretical questions can be
illustrated with specific examples. It makes things explicit, and people
can point at concrete things as good or bad.

| I'll tried to get rid of
| that missing link this sample is only theoretic, but the code really
| exists and is over 1000 lines long.
|
| I understood how to transmit data to a class, but I do not understood
| how that class could access an SQL object, that is allready opened at
| a other class without getting into troubles with sqlite.

The "SQL object" is just more data. Pass it to the class instance like
any other argument.

| For my understood, the newsgroup isn't a place only to solve concrete
| problems. I think you're not only a "helpdesk" :), If I'm at the wrong
| group to get some Ideas how to solve my "issues"

If you're after theoretic advice, please ask it in the context of real
working example code. It removes a lot of vagueness and ambiguity.
Especially if you are having trouble with English "wording": code
examples that run are much easier to discuss.

Cheers,
--
Cameron Simpson <[email protected]>

The US government can't make a penny for a penny. How can we make RFID
tags for a penny?
- overhead by WIRED at the Intelligent Printing conference Oct2006
 
A

Alexander Blinne

At this point I think i could just refer to my other 2 postings and urge
you to read them again. They offer the idea of encapsulating the
function QuerySqlite into a method of an object that can be passed over
to some object (possibly throu the __init__-method) and store it in an
attribute of that other object. Those other objects can then simply call
the method belonging to the object.
If you really don't understand what I mean by this maybe you should
learn a bit about the basics of object-oriented programming.
Some pseudo-code illustrating this idea (which differs a bit from the
first singleton-like suggestion):

datastore.py:

class Datastore(object):
def __init__(self, some_args):
#do all things needed to open datastore and store everything to
#self.something and self.someotherthing

def query(self, query, *values):
#execute query with values inserted
#using self.something and self.someotherting
#return result

modbus.py:

class Modbus(self):
def __init__(self, datastore):
#store the argument datastore to an attribute of the newly
#created object
self.datastore = datastore

def read_bus(self, sensor):
#read from bus the value of sensor and return value

def read_temp_and_store(self, sensor):
#read and store
value = self.read_bus(sensor)
self.datastore.query("some query string", value)

scheduler.py:

class Scheduler(object):
def __init__(self, datastore, modbus):
#store the arguments datastore and modbus to attributes
#of the newly created object
self.datastore = datastore
self.modbus = modbus
#maybe read some config data from datastore
self.config = self.datastore.query("some initialising query if
necessary")

def do_things(self):
#do things you wanna do, perhaps in some loop or in a thread or
#something, does not really matter.
#Threading may require locking of some kind, but this also is
#not really related to your problem as I understand ist.
self.modbus.read_temp_and_store("sensor1")

main.py:

from scheduler import Scheduler
from datastore import Datastore
from modbus import Modbus

def main():
datastore = Datastore(some_args)
modbus = Modbus(datastore)
scheduler = Scheduler(datastore, modbus)

scheduler.do_things()

if __name__=="__main__":
main()

Please feel free to ask specific questions about this approach.

merry christmas everyone
Alexander Blinne
 
D

Dave Angel

Hello Dave,

Thank you, for your help, I'll try my best.

To all others, PLEASE be pleasant with my nescience, I'll tried to describe not a specific error at my Program. I'll tried to get rid of that missing link this sample is only theoretic, but the code really exists and is over 1000 lines long.

I understood how to transmit data to a class,

This is an example where terminology is messing up communication. To me,
transmission implies communication between two different active systems,
like across a network, or at least between processes. A class isn't
active at all, it's a holding place for attributes (class-attributes),
and it's indirectly a description of what instances will look like.
Most likely what you mean is you know how to pass data to an instance
method of a class. Or how to set class-attributes, or
instance-attributes, which are not the same thing.
but I do not understood how that class could access an SQL object, that is allready opened at a other class without getting into troubles with sqlite.

I don't know sqlite, so I don't know what might constitute 'getting into
troubles.' But a class method (not the class itself) is given a self
object, and other parameters, and if one of those parameters is an SQL
object, it can be manipulated there just as readily as wherever that SQL
object was first discovered.
For my understood, the newsgroup isn't a place only to solve concrete problems. I think you're not only a "helpdesk" :), If I'm at the wrong group to get some Ideas how to solve my "issues"

We're a disjoint bunch of volunteer teachers, and a bunch of learners,
and each of us spends some of our time in each role. Most people spend
quite a while "learning," or at least lurking, before asking questions.
Then a bunch more before being ready to answer questions and make useful
comments. But it's not a linear process, and nobody takes a test to
qualify for "teaching." The goal of this forum is to field the
questions which are above the level of python-tutor.

More importantly than the "purpose" of the forum is that the nature of a
forum is that you have to get the interest of enough readers that
somebody knowledgeable about your problem will actually jump in and help
solve it. There are a number of ways to discourage useful responses,
and one of them is to write confusing comments or non-working code. Of
course, confusing phrasing can be a language issue, or it can be an
understanding issue. But it's easy to tell when there's non-working
code. If it doesn't run, it's not working. Is that a problem? Depends
on the nature of the question.

Ps.: DaveA I don't know how to say it, but I treasure your great work here, giving such detailed good answers.

To the others, he's referring in part to an offline apology, where I
offered some detailed suggestions.
PPs.: I know, that my codingstyle isn't that great, I've haven't programmed the last two years. You're welcome to guess what I've worked 8 years long. :) you will laugh till you fall of your keyboard :p

PPPs.: I' will use that day to check out the PEP's and correct my coding style, and naming.

http://www.python.org/dev/peps/pep-0008/
describes coding guidelines. But please note that the places where
I was correcting your capitalization, it was only a small part of pep8,
the parts which are most likely to be causing confusion between you and
us. It's important to get your mind around the differences between
modules, classes, instances, attributes, etc., and when we use the
appropriate capitalization, it tends to show we're understanding it.

There are other things in pep8 that haven't been mentioned here, and
there are many things I don't follow. But for example I use 4 spaces
for indenting, and never tabs. Some people prefer tabs, and python
permits it. But mixing them is real hazardous, since code may seem to
be doing one thing and actually do another if the way you expand the
tabs is different than the way the compiler does. But the real problem
online is that your tabs may work great with your toolset, but once you
put it in a message, they may work entirely differently to the hundreds
of different toolsets we use to view and/or try out your code.

Pep8 recommends a particular style within a function name, separating
'words of a name by underscore. I happen to loathe that style, so I'm
clearly not the one who would critique someone for not following the
guideline. I say getFile(), the pep says get_file().

Anyway, Pep8 is a guideline.


I think you need a tutorial, badly. Two years of not programming is no
big deal, but you don't seem to understand a number of very fundamental
concepts, or at least not understand them well enough to express them.
The real question is probably what other language did you use, and were
you a master at it, or just dabble. No offense intended, you've never
said whether this is your primary career, nor how old you are, nor any
other thing which might let us guess.

I like software, (though I took 8 years off to run a photography
business (and moonlighted about 3 years of the time to supplement the
income). But I insist on creating a useful mental model of how a
language and/or system operates. Then I modify that model when things
prove to be wrong. So a tutorial that might be good for me might not be
the right one for you. The two that I'd suggest are:

http://docs.python.org/tutorial/index.html - the official one
http://www.alan-g.me.uk/ - Alan Gauld's tutorial. I don't know it, I
just see how much help Alan is here and elsewhere, and Assume the
tutorial is similar

I'm going to continue in another message later, trying to do a "jump in
the middle and answer some questions which may have been asked, or
should have, or something."
 
D

Dave Angel

Python is a flexible language, but manages to let one write readable
code even while using that flexibility. It does, however, require that
one gets a grasp of some concepts that may differ greatly, either in
implementation or in name, from other languages. Every language has its
quirks and constraints, but Python is usually about self-discipline,
rather than the language forcing it down our throat.

So you can write object-oriented code, or you can (for the most part)
forget that objects exist, and use them without realizing. You can
write functional code (mostly), or you can ignore that concept. The
main thing I can think of that you can't do is "goto." Unlike C,
BASIC, and assembler.

Python 2.7, if not stated otherwise. 3.x has some new rules. I'm going
to assume you're familiar with lots of concepts, and have played with
the language. So I'm not going to define print, or the plus sign.

So what are the building blocks? Everything in Python is an object, or
becomes one soon after you look at it. Open a file, you get an object.
Do some arithmetic, you get an object.

So how do you create one? As soon as you launch the compiler on your
source script, you're creating a module object. inside that module
object are attributes that we usually call global variables, and other
attributes we call functions. And maybe attributes we call classes.
These are creating while compiling that script. How do we reference
those objects? By using their names. That's what's meant by global,
they're universally accessible. Oops, that's until we start making more
modules, which we'll get to later.

Python also has a bunch of modules it already loaded for us, including
the one called builtins. Those objects appear magically in every
module, so they appear global as well. What about objects in some
library function? First we have to import the module, then we reference
the object by both the module name and the name in THAT global space.
(That's why the word global was probably unfortunate). So to get at the
function object called "sin" in the module called "math", we do the
following two statements:

import math
print math.sin(1)

What did that import do? It simply created a new global called math,
and bound it to the module by that name, compiling it and loading it if
necessary. Once we have imported it, we can use ALL of its globals
(functions, variables, and classes, mostly) simply by the magic of the
dot. math.sin means look up the global math, then within that object
look up the attribute sin. The syntax doesn't care that math is a
module, the same syntax would work if math was a file you just opened,
and sin was a File method. So to read data from a file, we might do

myfile = open("filename")
print myfile.read(10)

Now, we glibly used 1,10, and "filename" in the above. What are they?
They're literal objects. In the source code you give enough information
to create an object of a particular builtin type (like int and str), and
by the time the code is running, these objects are created in some
magical space we might call "the literal pool." How that works doesn't
matter to anybody except to the guys building the compiler/interpreter.

So some names are global, and some are attributes. I think that's it
for names. There are constraints on what characters make up a name
(though in 3.x, that restricts one to a few hundred thousand symbols or
so), but that's about it.

Do all objects have names? Nope. We also have the notion of
containers, and we have special syntax to access them. So a list can
reference dozens, or millions of objects, and none of them have an
independent name. And the list might not either, if it came from a
literal print [1,2,3].

What about a dictionary. Funny thing, a dictionary works much like
attributes, only with a special syntax, and no restrictions on what the
keys can be. In fact, under the covers, attributes are just items in an
invisible dictionary of an ordinary object. (Note that invisible means
you don't usually care, in Python it's nearly always possible to peek
through the keyhole to see these things, but it can be very confusing,
and even harder to discuss)

Now we've been glibly referring to global items "having values" and
attributes "having values" and in fact much of the literature refers to
variables. But in a real sense, there are no variables at all. There
is what's called binding. A name is bound to an object. Any object,
created any way, and located any way. A list entry is bound to an
object. So the object itself has no name. it has type, and it probably
has attributes (actually it always does, but they may be "invisible").
But a name might be bound to that object at some time, or ten names, or
none at all. And the object (probably) ceases to exist once there's no
way to find it. If it's been bound to three names, and you rebind all
three names, then the object goes away after the third name is rebound.
If its bound to a slot in a list, and also in a dictionary, and also in
a name, then it won't go away till all of those go away, or get rebound.

An important concept is mutation. Many object, such as ints and strs,
are immutable, meaning they cannot change. You can create a new object
very similar to the original, and rebind names from first to the second:
a = "Peter"
a = a + " Punkin Eater"

So a is rebound to a new object, and the Peter object will go away.

But if we have a mutable object, like a list, then we can modify the
single object without having to rebind it.
a = [1,2,3]
a.append(42)

This "changed a" but not really. It changed the object that a is bound
to. This distinction is a primary reason why the term variable is
misleading.

Now I get to modules, which are really most interesting when you start
writing the yourself. Then, instead of following examples in the module
description, you have to decide how the module's "public" interfaces are
going to work, and why.

Back to the example
import math
print math.sin(1)

Suppose that we use that function a lot. Then we might wish to avoid
prepending it with the module name every time. The direct way to do
that is simply
sin = math.sin

This creates a new global name, and binds it to the object which was
already accessible as math.sin . Notice that there are now two ways to
get at that function, and also notice that we have no called the
function yet (no parentheses).

The shorthand for this is
from math import sin

It does the same thing, but without actually defining a global called math.

Please avoid the funny mechanism: from math import * It gives the
reader no clue as to what symbols are now visible as globals. And some
of those symbols might happen to have names that conflict with others we
do want. The only time to do this is when a module is specifically
designed that way. it can be coded in such a way as to restrict the
names that come in. I still don't like it, but the docs are probably
written that way.

So if you write your own, please use a lowercase leading letter in the
filename.

Now, to reference stuff in that other module, you add an import, just
like you did with math.
import mymodule
result = mymodule.myfunction(arg1, arg2)

Let's assume you use
from mymodule import myfunction

You now have an extra name bound to the same object as myfunction was in
the other module.

For constants and for functions, this is pretty straightforward. But
what happens if somebody changes one of those globals? that depends if
they rebind it, or they mutate it? If they rebind it, you'll still be
referring to the original version. While if they mutate it, you'll see
the changes, because you have an extra name bound to the same object.

I haven't mentioned writing classes yet, and describing them will take
lots more words.
 
D

Dave Angel

(Part 3 of my dissertation; I hope it's useful for you in particular)

Up to now in my discussion, it wasn't usually important to know that
everything is a class. You just know that everything has attributes,
and that you use the dot notation to get at an attribute. So what if
"%x".format() is a class method of the class str, you can just learn
"this is how you can format text". But once you learn how to write
classes, it starts to all come together.

class MyClass (myParentClass):

This line, and all indented lines below it, constitute a class. The
defs inside are functions, but they're also methods, with special
behavior of the first parameter, called 'self' by convention. So a def
might look like:
def myMethod(self, arg1):
return arg1 * 2

Now, if somebody has an instance of your class, they can call this
method like:
myinstance.myMethod(42)
and the return value will be 84. This is remarkably like the notation
we used before inside a module. So a class *could* be used just to
encode the namespace. But the power comes when there are attributes on
the object, and when self is used to get at those attributes. In that
situation, the self can refer to all kinds of data. In a sense you
could think of that data as being like the globals of a module, except
for one very important thing. There's only one instance of the module,
so those globals are shared between everyone. But with an instance, you
can have many instances, and each has its own set of attributes.

Simplest way to illustrate this is with a MyFile class. There's already
a very nice class in the standard library, with a builtin function
open() to create a new instance. But we can pretend to write such a
class, and see how making it a class is probably better than any other
way to code the functionality. And in fact, many people have done
something like that, to reference something analogous to a file.

When we open a class, some code somewhere has to keep track of the
system's file handle, the file position, the mode of operation, any
buffers that might be used, etc. Whatever that data is, if it's kept in
an instance, then it's possible to open multiple files at the same time,
some for writing, some for reading, etc. So how might we go about doing
that?

class MyFile(object):
def __init__(self, filename, mode):
self.filename = filename #remember the filename, in case
someone wants it
self.handle = someOScall(filename, mode) #do whatever it
might take to actually open a file
self.position = 0
self.opened = True
def read(self, size):
data = someOScallToRead(self.handle, self.size) #do whatever
it takes to read some data
self.position += size #probably it's more
complicated than this
return data

Now __init__() is a special method name. It's called implicitly when an
object of this class is made. A newly created dummy object of the right
type is passed to __init__() as self, and we want to stuff that object
with the appropriate attributes (typically a dozen or more).

read() is a simple method, although it could be *much* more complex for
a real file. It might do buffering, or it might translate characters,
or almost anything. But by the time it's called, we know the object's
__init__() method has been called, a file is open, the handle
initialized, etc.

So now the user can create two different objects:
file1 = MyFile("firstfile.txt", 12)
file2 = MyFile("otherdirectory/secondfile.txt", 49)

and can unambiguously read from whichever one she likes.

This notion that the attributes of the object carries all its necessary
data, and that the user of the class need not know any of the details is
the reason one can readily write code in separate modules that knows
little about the internals. Just pass the necessary object around, and
if the class was done right, it'll be ready to do all the operations
defined on it.

Hope this helps. It's just barely scratched the surface of what's possible.
 
R

Ranting Rick

Pep8 recommends a particular style within a function name, separating
'words of a name by underscore.  I happen to loathe that style, so I'm
clearly not the one who would critique someone for not following the
guideline.  I say getFile(), the pep says  get_file().

Slightly off topic, but still quite relevant: I happen to like that
style for public methods (even though Python has no real public/
private methods).

class Foo():
def __init__(self)
def __secretMethod() # Secret handshake required!
def _privateMethodOrAccessor() # Self only.
def sharedMethod() # Self and/or descendants only.
def public_method() # Total whore.
 
P

prilisauer

Hey :p I think I should rename the threads name into a new "Doc" project,
I'm sure It won't take much time to fill a book with our knowledge.

Thanks to Rick, you have Posted exactly what I wanted to ask. I know the that
__variable = 'xyz'
_variable = 'xyz'

are used to make them private, but I haven't found it for methods. Thanks :)

I also don't think you're off topic! It's a big grey scale :) and for me the first post till the last one is a part of my "question"

PEP, is nice, it tooks me a few days to get trough all your input and my code. Anyway is there also a best practice for naming? eg.: module_class_sub() or wording? eg.: socket: send() recv() -> recv is kept short. according PEP8??


It seems, my english slowly getting better again, If my colleagues would see what I'm writting here they won't belive me. I've worked at the Pharmaceutical IT and made Codereviews and programming for medical software. I stillcan't belive what I've forgotton the last two years. But still PEP etc. isn't far that hard written like pharm eu, usp, and 21CFR. Shame on me, but Iwill come back, after I've finished.

BR
 
P

prilisauer

Hello Steven,

to "learn python" I've bought a book, and it's not a "thin" one :) it's more a 788p. long documentation about python.

BUT!!!!! I have to say: The autor started using the "self." argument at the chapter classes. So You've shown me the book descr. non "correct" way. Better using this book heating my home?! :)

Patrick
 
D

Dave Angel

Hello Steven,

to "learn python" I've bought a book, and it's not a "thin" one :) it's more a 788p. long documentation about python.

BUT!!!!! I have to say: The autor started using the "self." argument at the chapter classes. So You've shown me the book descr. non "correct" way. Better using this book heating my home?! :)

Patrick

You still are being imprecise. You don't give a title or author, and
you refer to the "chapter classes" whatever that is. Do you mean the
chapter about classes? If so, that's exactly where 'self' should be
introduced.

How about copying an example function that uses self, that you think is
incorrect ? If it is incorrect, perhaps we should give the author some
feedback.

We all make mistakes, like my referring to class methods when I meant
instance methods. But I didn't figure it was time to introduce class
methods, so I wasn't trying to make the distinction. My error.
 
P

prilisauer

By the way i haven't add the Title because it's a german only book named
"Python 3: Das umfangreiche Handbuch, Published by Galileo Computing"

and also, because I've registered to first check if the Autor has allready published a update. Too many information's could ocurre in an avalanche

I see a big failure:

1. I answer to quick
 
P

prilisauer

By the way i haven't add the Title because it's a german only book named
"Python 3: Das umfangreiche Handbuch, Published by Galileo Computing"

and also, because I've registered to first check if the Autor has allready published a update. Too many information's could ocurre in an avalanche

I see a big failure:

1. I answer to quick
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top