[issue45483] pure Python class that has been registered as a `collections.abc.Sequence` can't be recgnized by the match statement without the `_abc` module

2021-10-15 Thread Raymond Hettinger


Change by Raymond Hettinger :


--
nosy: +rhettinger

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue45483] pure Python class that has been registered as a `collections.abc.Sequence` can't be recgnized by the match statement without the `_abc` module

2021-10-15 Thread GalaxySnail


New submission from GalaxySnail :

Pure Python class that has been registered as a `collections.abc.Sequence` 
can't be recgnized by the match statement without the `_abc` module.

For example:

```
>>> from test.support.import_helper import import_fresh_module

>>> collections_abc_with_c_abc = import_fresh_module(
... "collections.abc", fresh=["_collections_abc", "abc", "_abc"])

>>> class MyList:
... def __init__(self, iterable):
... self.list = list(iterable)
... def __len__(self):
... return len(self.list)
... def __getitem__(self, item):
... return self.list[item]
...
>>> collections_abc_with_c_abc.Sequence.register(MyList)

>>> match MyList(range(3, 10)):
... case [x, *_]:
... print(x)
... case _:
... print("not a sequence")
...
3

>>> collections_abc_with_py_abc = import_fresh_module(
... "collections.abc", fresh=["_collections_abc", "abc"], blocked=["_abc"])
>>> class MyList:
... def __init__(self, iterable):
... self.list = list(iterable)
... def __len__(self):
... return len(self.list)
... def __getitem__(self, item):
... return self.list[item]
...
>>> collections_abc_with_py_abc.Sequence.register(MyList)

>>> match MyList(range(3, 10)):
... case [x, *_]:
... print(x)
... case _:
... print("not a sequence")
...
not a sequence
```

It seems to be caused by 
https://github.com/python/cpython/commit/069e81ab3da46c441335ca762c4333b7bd91861d
 , only `tp_flags` are checked in the `MATCH_SEQUENCE` opcode. `Mapping` has 
the same problem.

--
messages: 404011
nosy: GalaxySnail
priority: normal
severity: normal
status: open
title: pure Python class that has been registered as a 
`collections.abc.Sequence` can't be recgnized by the match statement without 
the `_abc` module
type: behavior
versions: Python 3.10, Python 3.11

___
Python tracker 
<https://bugs.python.org/issue45483>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41838] Value error is showing in docset python (class)

2020-09-28 Thread Eric V. Smith

Eric V. Smith  added the comment:

If you can provide the information requested, please reopen this issue. In the 
meantime, I’m closing it.

--
resolution:  -> rejected
stage:  -> resolved
status: pending -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41838] Value error is showing in docset python (class)

2020-09-24 Thread Eric V. Smith


Change by Eric V. Smith :


--
status: open -> pending

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41838] Value error is showing in docset python (class)

2020-09-23 Thread Eric V. Smith


Eric V. Smith  added the comment:

It would be helpful if you can:
- simplify the example
- attach the simplified code to this issue
- show how the code runs with no errors, and how you invoke it
- show how you invoke the code when it does have errors

Please do no attach images: they are not friendly to users using accessibility 
software, and they're impossible to copy/paste/search.

--
nosy: +eric.smith

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41838] Value error is showing in docset python (class)

2020-09-23 Thread Mohit Kumar


New submission from Mohit Kumar :

https://github.com/python/bugs.python.org/issues/55

--
assignee: docs@python
components: Documentation
messages: 377362
nosy: docs@python, mkay6122
priority: normal
severity: normal
status: open
title: Value error is showing in docset python (class)
type: behavior
versions: Python 3.8

___
Python tracker 
<https://bugs.python.org/issue41838>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: i don't understand this python class

2020-06-29 Thread DL Neil via Python-list

On 30/06/20 5:14 AM, joseph pareti wrote:

I have piece of code with constructs as follows:

*class* *SentimentNetwork**:*

 *def* __init__*(*self*,* reviews*,* labels*,* hidden_nodes *=* 10*,*
learning_rate *=* 0.1*):*
 np*.*random*.*seed*(*1*)*
self*.*init_network*(**len**(*self*.*review_vocab*),*hidden_nodes*,*
1*,* learning_rate*)*

 *def* init_network*(*self*,* input_nodes*,* hidden_nodes*,* output_nodes
*,* learning_rate*):*
 # Store the number of nodes in input, hidden, and output layers.
 self*.*input_nodes *=* input_nodes
 self*.*hidden_nodes *=* hidden_nodes
 self*.*output_nodes *=* output_nodes

which makes me think about the redundant usage of* init_network:*

1. as a method, AND
2. as a property



Let's imagine this code-functionality, but where all of the 
initialisation is performed in the single __init__ method:-


- there would be four lines of code instead of eight, saving typing-time 
and reading-time
- when reading the code, we would not have to 'jump' our eyes from 
__init__() to init_network, just to see what happens at instantiation


So, why bother?
(is that the nub of your question?)

Consider now the pertinent four lines:

- seed the PRNG (Pseudo-Random Number Generator)
- set number of input_nodes
- set number of hidden_nodes
- set number of output_notes

per my favorite (hi-brown and highly-technical) TV program(me): "which 
of these is not like the others?"


Add to such thinking, that there is apparently much more in the 
initialiser than illustrated (presumably for brevity - thanks!), and you 
can comprehend that there are several *different* functions that all 
have to happen upon instantiation.


So, although init_network() as a separate method is *functionally* 
unnecessary, by separating those tasks from 'everything else that has to 
happen' (and presumably also bunching groups of those tasks together 
under applicable headings!) is a very helpful *documentation* technique 
- in fact, I put it to you, that the name of the method is more helpful 
to a reader, than is the explanatory comment! Your thoughts?


(which #comment 'should' be a docstring, BTW)


The word "property" may have a slightly different definition in Python 
than in other programming languages you have used. If that part of the 
question hasn't been adequately-covered (albeit en-passant) please 
explain further...



Finally, please be aware that there is a Python-Tutor Discussion List 
for the pleasure of both learners and tutors.

--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: i don't understand this python class

2020-06-29 Thread Calvin Spealman
You are misreading the original example. `init_network` is defined as a
method on the class, and called in its initializer. There is no property
named "init_network".

On Mon, Jun 29, 2020 at 1:18 PM joseph pareti  wrote:

> I have piece of code with constructs as follows:
>
> *class* *SentimentNetwork**:*
>
> *def* __init__*(*self*,* reviews*,* labels*,* hidden_nodes *=* 10*,*
> learning_rate *=* 0.1*):*
>
>
>
> np*.*random*.*seed*(*1*)*
>
>
>
>self*.*init_network*(**len**(*self*.*review_vocab*),*hidden_nodes*,*
> 1*,* learning_rate*)*
>
>
>
>
>
>
>
> *def* init_network*(*self*,* input_nodes*,* hidden_nodes*,*
> output_nodes
> *,* learning_rate*):*
>
> # Store the number of nodes in input, hidden, and output layers.
>
> self*.*input_nodes *=* input_nodes
>
> self*.*hidden_nodes *=* hidden_nodes
>
> self*.*output_nodes *=* output_nodes
>
> which makes me think about the redundant usage of* init_network:*
>
>1. as a method, AND
>2. as a property
>
> So far I have only seen codes where the 2 things are separated, e.g. :
>
> *import* insurance *as* ins
>
> *class* *Vehicle**:*
>
> *def* __init__*(*self*,* speed*,* make*):*
>
> self*.*speed *=* speed
>
> self*.*make *=* make
>
> *class* *car**(*Vehicle*):*
>
> *def* __init__*(*self*,* speed*,* make*):*
>
> Vehicle*.*__init__*(*self*,* speed*,* make*)*
>
> self*.*insurance *=* ins*.*calc*(*make*)*
>
> *def* show_out*(*self*):*
>
> *print**(*'vehicle is '*,*self*.*make*,*' insurance premium
> '*,*self
> *.*insurance*)*
>
> *def* claim*(*self*,* discount*):*
>
> X *=* self*.*insurance *+* discount
>
> *return* X
>
>
> And hence I am not sure about the behavior of the first code in this email.
> --
> Regards,
> Joseph Pareti - Artificial Intelligence consultant
> Joseph Pareti's AI Consulting Services
> https://www.joepareti54-ai.com/
> cell +49 1520 1600 209
> cell +39 339 797 0644
> --
> https://mail.python.org/mailman/listinfo/python-list
>
>

-- 

CALVIN SPEALMAN

SENIOR QUALITY ENGINEER

cspea...@redhat.com  M: +1.336.210.5107
[image: https://red.ht/sig] 
TRIED. TESTED. TRUSTED. 
-- 
https://mail.python.org/mailman/listinfo/python-list


i don't understand this python class

2020-06-29 Thread joseph pareti
I have piece of code with constructs as follows:

*class* *SentimentNetwork**:*

*def* __init__*(*self*,* reviews*,* labels*,* hidden_nodes *=* 10*,*
learning_rate *=* 0.1*):*



np*.*random*.*seed*(*1*)*



   self*.*init_network*(**len**(*self*.*review_vocab*),*hidden_nodes*,*
1*,* learning_rate*)*







*def* init_network*(*self*,* input_nodes*,* hidden_nodes*,* output_nodes
*,* learning_rate*):*

# Store the number of nodes in input, hidden, and output layers.

self*.*input_nodes *=* input_nodes

self*.*hidden_nodes *=* hidden_nodes

self*.*output_nodes *=* output_nodes

which makes me think about the redundant usage of* init_network:*

   1. as a method, AND
   2. as a property

So far I have only seen codes where the 2 things are separated, e.g. :

*import* insurance *as* ins

*class* *Vehicle**:*

*def* __init__*(*self*,* speed*,* make*):*

self*.*speed *=* speed

self*.*make *=* make

*class* *car**(*Vehicle*):*

*def* __init__*(*self*,* speed*,* make*):*

Vehicle*.*__init__*(*self*,* speed*,* make*)*

self*.*insurance *=* ins*.*calc*(*make*)*

*def* show_out*(*self*):*

*print**(*'vehicle is '*,*self*.*make*,*' insurance premium '*,*self
*.*insurance*)*

*def* claim*(*self*,* discount*):*

X *=* self*.*insurance *+* discount

*return* X


And hence I am not sure about the behavior of the first code in this email.
-- 
Regards,
Joseph Pareti - Artificial Intelligence consultant
Joseph Pareti's AI Consulting Services
https://www.joepareti54-ai.com/
cell +49 1520 1600 209
cell +39 339 797 0644
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to instantiate a custom Python class inside a C extension?

2020-04-01 Thread MRAB

On 2020-04-01 13:42, Musbur wrote:

Hi guys,

I'm wondering how to create an instance of an extension class I wrote.
There's a minimal self-contained C module at the bottom of this post
which exports two things: 1) a class Series, and 2) a function
make_series() which is supposed to create a Series object on the C side
and return it. The make_series function uses PyObject_New() and
PyObject_Init() to create the new instance, but all it produces is some
kind of zombie instance which tends to crash the application with a
segfault in real life. When instantiated from Python using Series(), I
get a well-behaved instance.

I've sprinkled the New, Init and Finalize functions with fprintf()s to
see what happens to the object during its lifetime.

When I run this test script:

  from series import *

  print("From Python")
  s1 = Series()
  del s1

  print("\nFrom C")
  s2 = make_series()
  del s2

I get this output:

  From Python
  New Series at 0x7f89313f6660
  Init Series at 0x7f89313f6660
  Finalize Series at 0x7f89313f6660

  From C
  Finalize Series at 0x7f89313f6678

So when created from C, neither the "new" nor the "init" functions are
called on the object, only "finalize". No wonder I get segfaults in the
real life application.

So how is this done right? Here's the C module:


[snip]

Try this instead:

#include 

typedef struct {
PyObject_HEAD
void* data;
} SeriesObject;

static PyTypeObject SeriesType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "_Series",
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
.tp_doc = "SeriesObject (msec, value) object",
};

PyObject* make_series(PyObject* unused) {
SeriesObject* series;

series = PyObject_New(SeriesObject, );
series->data = NULL;
fprintf(stderr, "New SeriesObject at %p\n", series);

return (PyObject*)series;
}

static void Series_dealloc(PyObject* self_) {
SeriesObject* self;

self = (SeriesObject*)self_;
fprintf(stderr, "Deallocate SeriesObject at %p\n", self);

PyObject_DEL(self);
}

PyObject* Series_new(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
SeriesObject* self;

self = (SeriesObject*)type->tp_alloc(type, 0);
self->data = NULL;
fprintf(stderr, "New Series at %p\n", self);

return (PyObject*)self;
}

static PyMethodDef Series_methods[] = {
{NULL, NULL, 0, NULL}
};

static PyMethodDef module_methods[] = {
{"make_series", (PyCFunction)make_series, METH_NOARGS,
  "Instantiate and return a new SeriesObject object."},
{NULL, NULL, 0, NULL}
};

static PyModuleDef series_module = {
PyModuleDef_HEAD_INIT,
"series",
"Defines the SeriesObject (time, value) class"
,
-1,
module_methods
};

PyMODINIT_FUNC PyInit_series(void) {
PyObject* m;

m = PyModule_Create(_module);

SeriesType.tp_dealloc = Series_dealloc;
SeriesType.tp_new = Series_new;
SeriesType.tp_methods = Series_methods;
if (PyType_Ready() < 0)
return NULL;

PyModule_AddObject(m, "Series", (PyObject*));

return m;
}
--
https://mail.python.org/mailman/listinfo/python-list


Re: How to instantiate a custom Python class inside a C extension?

2020-04-01 Thread Rhodri James

On 01/04/2020 18:24, Musbur wrote:

Am 01.04.2020 15:01 schrieb Rhodri James:

I believe you do it in C as you would in Python: you call the Series 
class!


pyseries = PyObject_CallObject((PyObject *)_type, NULL);


Well, that dumps core just as everything else I tried.

What does work, however, is calling PyType_Ready first:

     PyType_Ready(_type);
     pyseries = PyObject_New(Series, _type);
     PyObject_Init((PyObject *)pyseries, _type);o

I don't understand, though, why I have to do that and when. Didn't that 
already happen when the module was imported? Do I need to do it whenever 
I create a new instance in C?


It should have happened on your module being imported, the line was 
there in your code.  Stick a breakpoint on your module init function and 
see if it is being called.


(The "from thingy import *" always makes me nervous, but it shouldn't be 
responsible for this.)


--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Re: How to instantiate a custom Python class inside a C extension?

2020-04-01 Thread Musbur

Am 01.04.2020 15:01 schrieb Rhodri James:

I believe you do it in C as you would in Python: you call the Series 
class!


pyseries = PyObject_CallObject((PyObject *)_type, NULL);


Well, that dumps core just as everything else I tried.

What does work, however, is calling PyType_Ready first:

PyType_Ready(_type);
pyseries = PyObject_New(Series, _type);
PyObject_Init((PyObject *)pyseries, _type);o

I don't understand, though, why I have to do that and when. Didn't that 
already happen when the module was imported? Do I need to do it whenever 
I create a new instance in C?

--
https://mail.python.org/mailman/listinfo/python-list


Re: How to instantiate a custom Python class inside a C extension?

2020-04-01 Thread Rhodri James

On 01/04/2020 13:42, Musbur wrote:
So when created from C, neither the "new" nor the "init" functions are 
called on the object, only "finalize". No wonder I get segfaults in the 
real life application.


So how is this done right? Here's the C module:


I believe you do it in C as you would in Python: you call the Series class!

pyseries = PyObject_CallObject((PyObject *)_type, NULL);

--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


How to instantiate a custom Python class inside a C extension?

2020-04-01 Thread Musbur

Hi guys,

I'm wondering how to create an instance of an extension class I wrote. 
There's a minimal self-contained C module at the bottom of this post 
which exports two things: 1) a class Series, and 2) a function 
make_series() which is supposed to create a Series object on the C side 
and return it. The make_series function uses PyObject_New() and 
PyObject_Init() to create the new instance, but all it produces is some 
kind of zombie instance which tends to crash the application with a 
segfault in real life. When instantiated from Python using Series(), I 
get a well-behaved instance.


I've sprinkled the New, Init and Finalize functions with fprintf()s to 
see what happens to the object during its lifetime.


When I run this test script:

from series import *

print("From Python")
s1 = Series()
del s1

print("\nFrom C")
s2 = make_series()
del s2

I get this output:

From Python
New Series at 0x7f89313f6660
Init Series at 0x7f89313f6660
Finalize Series at 0x7f89313f6660

From C
Finalize Series at 0x7f89313f6678

So when created from C, neither the "new" nor the "init" functions are 
called on the object, only "finalize". No wonder I get segfaults in the 
real life application.


So how is this done right? Here's the C module:

#include 

typedef struct {
PyObject_HEAD
void *data;
} Series;

static PyObject *Series_new(PyTypeObject *type,
PyObject *args, PyObject *kw) {
Series *self;

self = (Series *) type->tp_alloc(type, 0);
self->data = NULL;
fprintf(stderr, "New Series at %p\n", self);
return (PyObject*)self;
}

static int Series_init(Series *self, PyObject *args, PyObject *kw) {
fprintf(stderr, "Init Series at %p\n", self);
return 0;
}

static void Series_finalize(PyObject *self) {
fprintf(stderr, "Finalize Series at %p\n", self);
}

static PyMethodDef series_methods[] = {
{NULL, NULL, 0, NULL}
};

static PyTypeObject series_type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "_Series",
.tp_basicsize = sizeof(Series),
.tp_flags = 0
| Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE,
.tp_doc = "Series (msec, value) object",
.tp_methods = series_methods,
.tp_new = Series_new,
.tp_init = (initproc) Series_init,
.tp_dealloc = Series_finalize,
};

/* To create a new Series object directly from C */
PyObject *make_series(void *data) {
Series *pyseries;
pyseries = PyObject_New(Series, _type);
PyObject_Init((PyObject *)pyseries, _type);
pyseries->data = data;
return (PyObject *) pyseries;
}

static PyMethodDef module_methods[] = {
{"make_series",  (PyCFunction)make_series, METH_NOARGS,
 "Instantiate and return a new Series object."},
{NULL, NULL, 0, NULL}
};

static PyModuleDef series_module = {
PyModuleDef_HEAD_INIT,
"series",
"Defines the Series (time, value) class"
,
-1,
module_methods
};

PyMODINIT_FUNC PyInit_series(void) {
PyObject *m;

m = PyModule_Create(_module);

if (PyType_Ready(_type) < 0) {
return NULL;
}
PyModule_AddObject(m, "Series", (PyObject*)_type);
return m;
}


--
https://mail.python.org/mailman/listinfo/python-list


NEED ASSISTANCE WITH PYTHON CLASS

2020-03-28 Thread gentleman . for . ever . and . ever
Hi, I need help with coding assignments (python to be exact) in school. I am 
willing to pay for your attention by the hour. Please email me at 
aifa...@protonmail.com if you’re interested. Please only reach out if you’re 
not a beginner. Trying to avoid the blind being led by the blind. Thanks!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to call a Python Class?

2016-05-03 Thread Ben Finney
David Shi via Python-list <python-list@python.org> writes:

> I found a Python class within an Open Source software.
> I would like to use it in my own Python script.
> I tried to import it, but I got following message.

Your text is mangled in transit. Please post only plain text messages
(avoid HTML or other “rich” content), so the formatting survives.

> from intersection import *Traceback (most recent call last):  File 
> "<pyshell#4>", line 1, in     from intersection import *ImportError: 
> bad magic number in 'intersection': b'\x03\xf3\r\n'
> Can any one help?

If we can see the exact code you tried, perhaps.

-- 
 \  “Holy hole in a donut, Batman!” —Robin |
  `\   |
_o__)  |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to call a Python Class?

2016-05-03 Thread Chris Angelico
On Wed, May 4, 2016 at 8:56 AM, David Shi via Python-list
<python-list@python.org> wrote:
> I found a Python class within an Open Source software.
> I would like to use it in my own Python script.
> I tried to import it, but I got following message.
> from intersection import *Traceback (most recent call last):  File 
> "<pyshell#4>", line 1, in from intersection import *ImportError: 
> bad magic number in 'intersection': b'\x03\xf3\r\n'
> Can any one help?
> Regards.

Did you get a .py file, or only a .pyc? Try deleting all .pyc files
that you downloaded, and try again.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


How to call a Python Class?

2016-05-03 Thread David Shi via Python-list
I found a Python class within an Open Source software.
I would like to use it in my own Python script.
I tried to import it, but I got following message.
from intersection import *Traceback (most recent call last):  File 
"<pyshell#4>", line 1, in     from intersection import *ImportError: 
bad magic number in 'intersection': b'\x03\xf3\r\n'
Can any one help?
Regards.
David
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to create an instance of a python class from C++

2014-03-12 Thread Stefan Behnel
Barry Scott, 11.03.2014 22:37:
 On 5 Mar 2014, at 00:14, Bill wrote:
 I can't figure out how to create an instance
 of a python class from 'C++':
 
 Why not use pycxx from http://sourceforge.net/projects/cxx/?
 
 This lib does all the heavy lifting for you for both python2 and python3.
 Has docs and examples.

Yes, tool support definitely helps here. I was going to suggest Cython
(also for obvious reasons), where the code that the OP posted would look
like this:

  def RegisterClass(class_decl):
  an = type(class_decl)()
  print(an.description())
  return 0

Clearly substantially simpler than the posted C code (and certainly safer,
faster and more correct) - although that doesn't really help me much with
understanding what the intention of this code is, looks rather weird...

Stefan


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to create an instance of a python class from C++

2014-03-11 Thread Barry Scott
On 5 Mar 2014, at 00:14, Bill galaxyblu...@gmail.com wrote:

 Hello:
 
 I can't figure out how to create an instance
 of a python class from 'C++':
 

Why not use pycxx from http://sourceforge.net/projects/cxx/?

This lib does all the heavy lifting for you for both python2 and python3.
Has docs and examples.

Barry
PyCXX maintainer.



 ( I am relatively new to Python so excuse some of
  the following. )
 
 In a .py file I create an ABC and then specialize it:
 
from MyMod import *
from abc import ABCMeta, abstractmethod
 
# Declare an abstract base class.
class Base(metaclass=ABCMeta):
Base class.
@abstractmethod
def description(self):
return From the base class.
 
# Declare a class that inerits from the base.
class Derived(Base):
Derived class.
def description(self):
return From the Derived.
 
# Register the derived class.
RegisterClass(Derived)
 
 Then from 'C++' (my implementation of RegisterClass)
 I try to create an instance
 
static PyObject *
RegisterClass( PyObject *, PyObject *args ) {   // This gets called ok.
 
PyObject *class_decl;
if( ! PyArg_ParseTuple(args, O, class_decl) )
return NULL;
Py_INCREF(class_decl);
 
PyTypeObject *typ = class_decl-ob_type;
 
// Tried this.
// PyObject *an = _PyObject_New(class_decl-ob_type); assert(an);
// PyObject *desc = PyObject_CallMethod(an,description,NULL); 
 assert(desc);
 
// Tried this.
// PyObject *an = PyType_GenericNew((PyTypeObject 
 *)class_decl-ob_type, NULL, NULL); assert(an);
// assert(class_decl); assert(class_decl-ob_type); 
 assert(class_decl-ob_type-tp_new);
 
// This returns something.
assert(class_decl); assert(class_decl-ob_type); 
 assert(class_decl-ob_type-tp_new);
PyObject *an_inst = 
 class_decl-ob_type-tp_new(class_decl-ob_type,NULL, NULL); assert(an_inst);
assert(class_decl-ob_type-tp_init);
 
// This crashes.
int ret = class_decl-ob_type-tp_init(an_inst,NULL, NULL); assert(ret 
 == 0);
// PyObject_CallMethod(an_inst,__init__,NULL);
// PyObject *an_inst = PyObject_CallMethod(class_decl,__new__,NULL); 
 assert(an_inst);
 
// Never get here.
PyObject *desc = PyObject_CallMethod(an_inst,description,NULL); 
 assert(desc);
char *cp = _PyUnicode_AsString(desc);
cerr  Description:  cp  endl;
 
return PyLong_FromLong(0);
}
 
static PyMethodDef MyModMethods[] = {
{ RegisterClass, RegisterClass, METH_VARARGS, Register class. },
{  NULL,   NULL,  0, NULL }
};
 
static struct PyModuleDef MyModMod = {
   PyModuleDef_HEAD_INIT,
   MyMod,// name of module
   NULL,// module documentation, may be NULL
   -1,
   MyModMethods,
   NULL,
   NULL,
   NULL,
   NULL
};
 
PyMODINIT_FUNC
PyInit_MyMod( void ) {
PyObject* m = PyModule_Create(MyModMod);
if( m == NULL )
return NULL;
return m;
}
 
int
main( int, char ** ) {
 
PyImport_AppendInittab( MyMod, PyInit_MyMod );
 
Py_Initialize();
 
const char *file_name = z.py;
FILE *fp = fopen(file_name,r);
if( fp ) {
PyRun_SimpleFileExFlags(fp,file_name,1,0);
}
 
Py_Finalize();
 
return 0;
}
 -- 
 https://mail.python.org/mailman/listinfo/python-list
 

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to create an instance of a python class from C++

2014-03-05 Thread Bill
 
 So far, so good.  The object that was passed in was the Derived
 class object.  Since you presumably only want class objects to be
 passed in, you might want to check that here using PyType_Check.

Yes. Will do.
 
  PyTypeObject *typ = class_decl-ob_type;
 
 In Python, you instantiate a class by calling it.  You should do the 
 same in C, using PyObject_CallFunction.  But as above, note that you
 want to call class_decl, not class_decl-ob_type.
 

Of course. That works.

Thanks.

Bill
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to create an instance of a python class from C++

2014-03-05 Thread Grant Edwards
On 2014-03-05, Ian Kelly ian.g.ke...@gmail.com wrote:
 On Tue, Mar 4, 2014 at 5:14 PM, Bill galaxyblu...@gmail.com wrote:
 Hello:

 I can't figure out how to create an instance
 of a python class from 'C++':

 ( I am relatively new to Python so excuse some of the following. )

 In a .py file I create an ABC and then specialize it:

 Why are you creating an ABC?

Because it was the first binary computer that did calculations with
electronic switching elements (gates), and it would be really cool to
have one! The ABC also pioneered the use of capciators as regenerative
storage elements (it's how DRAM still works today).

http://en.wikipedia.org/wiki/Atanasoff%E2%80%93Berry_Computer

It predated ENIAC, and it's clear that some of the features of ENIAC
were inspired by the ABC after John Mauchly visited Iowa State and saw
the ABC.

-- 
Grant Edwards   grant.b.edwardsYow! I can't decide which
  at   WRONG TURN to make first!!
  gmail.comI wonder if BOB GUCCIONE
   has these problems!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to create an instance of a python class from C++

2014-03-05 Thread Alister
On Wed, 05 Mar 2014 16:08:00 +, Grant Edwards wrote:

 On 2014-03-05, Ian Kelly ian.g.ke...@gmail.com wrote:
 On Tue, Mar 4, 2014 at 5:14 PM, Bill galaxyblu...@gmail.com wrote:
 Hello:

 I can't figure out how to create an instance of a python class from
 'C++':

 ( I am relatively new to Python so excuse some of the following. )

 In a .py file I create an ABC and then specialize it:

 Why are you creating an ABC?
 
 Because it was the first binary computer that did calculations with
 electronic switching elements (gates), and it would be really cool to
 have one! The ABC also pioneered the use of capciators as regenerative
 storage elements (it's how DRAM still works today).
 
 http://en.wikipedia.org/wiki/Atanasoff%E2%80%93Berry_Computer
 
 It predated ENIAC, and it's clear that some of the features of ENIAC
 were inspired by the ABC after John Mauchly visited Iowa State and saw
 the ABC.

But it was not programmable

the first programmable electronic computer was 'Colossus'
which was developed during WWII but remained classified by the UK govt 
for many years afterwards 

http://en.wikipedia.org/wiki/Colossus_computer





-- 
You are not dead yet.  But watch for further reports.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to create an instance of a python class from C++

2014-03-05 Thread Grant Edwards
On 2014-03-05, Alister alister.w...@ntlworld.com wrote:

 Why are you creating an ABC?
 
 Because it was the first binary computer that did calculations with
 electronic switching elements (gates), and it would be really cool to
 have one! The ABC also pioneered the use of capciators as regenerative
 storage elements (it's how DRAM still works today).
 
 http://en.wikipedia.org/wiki/Atanasoff%E2%80%93Berry_Computer
 
 It predated ENIAC, and it's clear that some of the features of ENIAC
 were inspired by the ABC after John Mauchly visited Iowa State and saw
 the ABC.

 But it was not programmable

True.  It had only one program that was hard-wired into it when it was
built as opposed to the external patch-cords and switches that were
used on machines like Colossus and ENIAC to alter the wiring.

 the first programmable electronic computer was 'Colossus' which was
 developed during WWII but remained classified by the UK govt for many
 years afterwards 

 http://en.wikipedia.org/wiki/Colossus_computer

-- 
Grant Edwards   grant.b.edwardsYow! Hmmm ... A hash-singer
  at   and a cross-eyed guy were
  gmail.comSLEEPING on a deserted
   island, when ...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to create an instance of a python class from C++

2014-03-05 Thread Gene Heskett
On Wednesday 05 March 2014 17:09:53 Grant Edwards did opine:

 On 2014-03-05, Alister alister.w...@ntlworld.com wrote:
  Why are you creating an ABC?
  
  Because it was the first binary computer that did calculations with
  electronic switching elements (gates), and it would be really cool to
  have one! The ABC also pioneered the use of capciators as
  regenerative storage elements (it's how DRAM still works today).
  
  http://en.wikipedia.org/wiki/Atanasoff%E2%80%93Berry_Computer
  
  It predated ENIAC, and it's clear that some of the features of ENIAC
  were inspired by the ABC after John Mauchly visited Iowa State and
  saw the ABC.
  
  But it was not programmable
 
 True.  It had only one program that was hard-wired into it when it was
 built as opposed to the external patch-cords and switches that were
 used on machines like Colossus and ENIAC to alter the wiring.
 
  the first programmable electronic computer was 'Colossus' which was
  developed during WWII but remained classified by the UK govt for many
  years afterwards
  
  http://en.wikipedia.org/wiki/Colossus_computer

What machine was it that had about 12,000 12AU7 vacuum tubes in it for 
logic?  They had one of those, adapted to read the output of a bed of 
photocells installed in a Harris sheet fed press on the SUI campus in the 
later 1950's.  I saw it running once, grading the test score sheets from 
the Iowa Tests that were being used in lieu of the high price per seat S-B 
IQ test in the Iowa schools.  It was IIRC a somewhat difficult test when 
they threw it at me in the 7th grade a decade earlier, they claimed the 
test score were interchangeable with the S-B scores, but I somehow managed 
a 147 on it at the time.

Cheers, Gene
-- 
There are four boxes to be used in defense of liberty:
 soap, ballot, jury, and ammo. Please use in that order.
-Ed Howdershelt (Author)
Genes Web page http://geneslinuxbox.net:6309/gene

NOTICE: Will pay 100 USD for an HP-4815A defective but
complete probe assembly.

-- 
https://mail.python.org/mailman/listinfo/python-list


How to create an instance of a python class from C++

2014-03-04 Thread Bill
Hello:

I can't figure out how to create an instance
of a python class from 'C++':

( I am relatively new to Python so excuse some of
  the following. )

In a .py file I create an ABC and then specialize it:

from MyMod import *
from abc import ABCMeta, abstractmethod

# Declare an abstract base class.
class Base(metaclass=ABCMeta):
Base class.
@abstractmethod
def description(self):
return From the base class.

# Declare a class that inerits from the base.
class Derived(Base):
Derived class.
def description(self):
return From the Derived.

# Register the derived class.
RegisterClass(Derived)

Then from 'C++' (my implementation of RegisterClass)
I try to create an instance

static PyObject *
RegisterClass( PyObject *, PyObject *args ) {   // This gets called ok.

PyObject *class_decl;
if( ! PyArg_ParseTuple(args, O, class_decl) )
return NULL;
Py_INCREF(class_decl);

PyTypeObject *typ = class_decl-ob_type;

// Tried this.
// PyObject *an = _PyObject_New(class_decl-ob_type); assert(an);
// PyObject *desc = PyObject_CallMethod(an,description,NULL); 
assert(desc);

// Tried this.
// PyObject *an = PyType_GenericNew((PyTypeObject 
*)class_decl-ob_type, NULL, NULL); assert(an);
// assert(class_decl); assert(class_decl-ob_type); 
assert(class_decl-ob_type-tp_new);

// This returns something.
assert(class_decl); assert(class_decl-ob_type); 
assert(class_decl-ob_type-tp_new);
PyObject *an_inst = 
class_decl-ob_type-tp_new(class_decl-ob_type,NULL, NULL); assert(an_inst);
assert(class_decl-ob_type-tp_init);

// This crashes.
int ret = class_decl-ob_type-tp_init(an_inst,NULL, NULL); assert(ret 
== 0);
// PyObject_CallMethod(an_inst,__init__,NULL);
// PyObject *an_inst = PyObject_CallMethod(class_decl,__new__,NULL); 
assert(an_inst);

// Never get here.
PyObject *desc = PyObject_CallMethod(an_inst,description,NULL); 
assert(desc);
char *cp = _PyUnicode_AsString(desc);
cerr  Description:  cp  endl;

return PyLong_FromLong(0);
}

static PyMethodDef MyModMethods[] = {
{ RegisterClass, RegisterClass, METH_VARARGS, Register class. },
{  NULL,   NULL,  0, NULL }
};

static struct PyModuleDef MyModMod = {
   PyModuleDef_HEAD_INIT,
   MyMod,// name of module
   NULL,// module documentation, may be NULL
   -1,
   MyModMethods,
   NULL,
   NULL,
   NULL,
   NULL
};

PyMODINIT_FUNC
PyInit_MyMod( void ) {
PyObject* m = PyModule_Create(MyModMod);
if( m == NULL )
return NULL;
return m;
}

int
main( int, char ** ) {

PyImport_AppendInittab( MyMod, PyInit_MyMod );

Py_Initialize();

const char *file_name = z.py;
FILE *fp = fopen(file_name,r);
if( fp ) {
PyRun_SimpleFileExFlags(fp,file_name,1,0);
}

Py_Finalize();

return 0;
}
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to create an instance of a python class from C++

2014-03-04 Thread Ian Kelly
On Tue, Mar 4, 2014 at 5:14 PM, Bill galaxyblu...@gmail.com wrote:
 Hello:

 I can't figure out how to create an instance
 of a python class from 'C++':

 ( I am relatively new to Python so excuse some of
   the following. )

 In a .py file I create an ABC and then specialize it:

Why are you creating an ABC?  Most Python classes do not use them.
Maybe you have a reason for it, but it's irrelevant to what you're
currently trying to do.

 Then from 'C++' (my implementation of RegisterClass)
 I try to create an instance

 static PyObject *
 RegisterClass( PyObject *, PyObject *args ) {   // This gets called 
 ok.

 PyObject *class_decl;
 if( ! PyArg_ParseTuple(args, O, class_decl) )
 return NULL;
 Py_INCREF(class_decl);

So far, so good.  The object that was passed in was the Derived
class object.  Since you presumably only want class objects to be
passed in, you might want to check that here using PyType_Check.

 PyTypeObject *typ = class_decl-ob_type;

Okay, now if class_decl is the class object that was passed in, then
class_decl-ob_type is the *type* of that class object -- the
metaclass, which in this case would be ABCMeta.  You probably don't
need this, because you want to instantiate Derived, not ABCMeta.

 // Tried this.
 // PyObject *an = _PyObject_New(class_decl-ob_type); assert(an);
 // PyObject *desc = PyObject_CallMethod(an,description,NULL); 
 assert(desc);

In Python, you instantiate a class by calling it.  You should do the
same in C, using PyObject_CallFunction.  But as above, note that you
want to call class_decl, not class_decl-ob_type.

PyObject_New doesn't do any initialization and is, I believe, meant to
be used when implementing types in C.
-- 
https://mail.python.org/mailman/listinfo/python-list


Python class and variable issue(newby question!)

2013-03-29 Thread Sam Berry
Hey, 

Im new to object orientated programming and have an issue with using classes. 
Im using the kivy module, a GUI creator , so posting the actual code may 
confuse. But an example of what im trying to achieve is below

class test()
s = 1

def test1()
global s
s = 2

def test2()
global s
s = 3

def test3()
global s
s = 4


class test4()

def printing()
print test().s

After been in the test()class  a choice of buttons allows the user to run 
either of the functions within it and sends us into the test4() class. Then 
another button runs printing().

However printing() always prints 1, even if the variable has been changed. Im 
guessing because  print test().s  redefines the variable. May be a very simple 
to solve problem, but i cant figure it out.

Any insights of how to get this working, or example code would be very helpful!

Thanks, Sam
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python class and variable issue(newby question!)

2013-03-29 Thread Chris Angelico
On Sat, Mar 30, 2013 at 8:12 AM, Sam Berry sambez...@hotmail.co.uk wrote:
 class test()
 s = 1

 def test1()
 global s
 s = 2

 def test2()
 global s
 s = 3

 def test3()
 global s
 s = 4

That's not a global, that's a class variable. But to give any more
specific help, it'd be helpful to have some actual working code -
twiddle your code until it's a nice simple example:

http://sscce.org/

Most likely, what you want is to make these functions into either
static methods or instance methods. Beyond that, hard to say exactly.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python class and variable issue(newby question!)

2013-03-29 Thread Benjamin Kaplan
On Fri, Mar 29, 2013 at 2:12 PM, Sam Berry sambez...@hotmail.co.uk wrote:
 Hey,

 Im new to object orientated programming and have an issue with using classes. 
 Im using the kivy module, a GUI creator , so posting the actual code may 
 confuse. But an example of what im trying to achieve is below

 class test()
 s = 1

 def test1()
 global s
 s = 2

 def test2()
 global s
 s = 3

 def test3()
 global s
 s = 4


 class test4()

 def printing()
 print test().s

 After been in the test()class  a choice of buttons allows the user to run 
 either of the functions within it and sends us into the test4() class. Then 
 another button runs printing().

 However printing() always prints 1, even if the variable has been changed. Im 
 guessing because  print test().s  redefines the variable. May be a very 
 simple to solve problem, but i cant figure it out.

 Any insights of how to get this working, or example code would be very 
 helpful!

 Thanks, Sam
 --


There are three different namespaces here: global, class, and local.
You're assigning to the global s, which exists outside the class. Do
print s instead of print test().s and you'll see your changed
value of s. If you want to change the value of s inside the class,
it's called test.s (notice that there's no parenthesis- that's
because s here is an attribute of the test class, not each instance of
test. The same value will be shared by all instances of that class).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python class and variable issue(newby question!)

2013-03-29 Thread Sam Berry
Thanks for the responses! My issue was sorted with Benjamins post, just 
printing s worked.

Cheers for the info though Chris, if i have any further issues il post them 
with some working code.

Sam
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python class and variable issue(newby question!)

2013-03-29 Thread Chris Angelico
On Sat, Mar 30, 2013 at 9:17 AM, Sam Berry sambez...@hotmail.co.uk wrote:
 Thanks for the responses! My issue was sorted with Benjamins post, just 
 printing s worked.

 Cheers for the info though Chris, if i have any further issues il post them 
 with some working code.

Awesome! Always happy to help out.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python class and variable issue(newby question!)

2013-03-29 Thread Steven D'Aprano
On Sat, 30 Mar 2013 08:24:00 +1100, Chris Angelico wrote:

 On Sat, Mar 30, 2013 at 8:12 AM, Sam Berry sambez...@hotmail.co.uk
 wrote:
 class test()
 s = 1

 def test1()
 global s
 s = 2

 That's not a global, that's a class variable.


/me thwacks Chris with a halibut.


Not only is class variable ambiguous, but Python uses different scoping 
rules for variables (name bindings) and attributes.

I don't know what language first decided to conflate object attributes 
and variables -- I suspect Java -- but it is actively harmful terminology 
(in Python at least, if not in general) and whoever invented it is bad 
and should feel bad.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python class and variable issue(newby question!)

2013-03-29 Thread Chris Angelico
On Sat, Mar 30, 2013 at 9:51 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On Sat, 30 Mar 2013 08:24:00 +1100, Chris Angelico wrote:

 On Sat, Mar 30, 2013 at 8:12 AM, Sam Berry sambez...@hotmail.co.uk
 wrote:
 class test()
 s = 1

 def test1()
 global s
 s = 2

 That's not a global, that's a class variable.


 /me thwacks Chris with a halibut.

Ow ow ow, I give in... I am suitably and appropriately thwacked.

 Not only is class variable ambiguous, but Python uses different scoping
 rules for variables (name bindings) and attributes.

Yes, I should have said class ATTRIBUTE. Sorry all! (Can I blame the
whole 8AM and still up thing? No? Mea culpa, anyhow.)

 I don't know what language first decided to conflate object attributes
 and variables -- I suspect Java -- but it is actively harmful terminology
 (in Python at least, if not in general) and whoever invented it is bad
 and should feel bad.

Agreed. Unfortunately it permeates a lot of programmer's vocabularies,
mine included.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python class and variable issue(newby question!)

2013-03-29 Thread Dave Angel

On 03/29/2013 06:17 PM, Sam Berry wrote:

Thanks for the responses! My issue was sorted with Benjamins post, just 
printing s worked.

Cheers for the info though Chris, if i have any further issues il post them 
with some working code.


In that case, you probably should add a line like:


s = None

at the beginning of the code, along with a description of what s is 
supposed to represent (especially since the name doesn't reveal much).


And you should remove the class variable s.  It'll just confuse things.

I guess this isn't the place to rail about non-const globals.

--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Class

2013-02-01 Thread Steven D'Aprano
Charles Hoskinson wrote:

 I'm developing an online course for beginning python programmers starting
 from basic syntax through object oriented design and GUI. I'd like to
 include some helpful community resources like Code Academy in the appendix
 and I was wondering if this community has some particular favorites they
 would highly recommend?


This is a helpful community resource:

- by email python-list@python.org
- by usenet comp.lang.python


Other useful resources include:

- the tutor mailing list tu...@python.org

- http://code.activestate.com/recipes/

- http://wiki.python.org/moin/



-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Class

2013-02-01 Thread Rodrick Brown
On Friday, February 1, 2013, Charles Hoskinson wrote:

 I'm developing an online course for beginning python programmers starting
 from basic syntax through object oriented design and GUI. I'd like to
 include some helpful community resources like Code Academy in the appendix
 and I was wondering if this community has some particular favorites they
 would highly recommend?


Udacity.com has a nice interactive CS course taught in Python.

 --
 http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Fool Python class with imaginary members (serious guru stuff inside)

2012-09-20 Thread Jure Erznožnik
I'm trying to create a class that would lie to the user that a member is in 
some cases a simple variable and in other cases a class. The nature of the 
member would depend on call syntax like so:
1. x = obj.member #x becomes the simple value contained in member
2. x = obj.member.another_member #x becomes the simple value contained in 
first member's another_member.

So the first method detects that we only need a simple value and returns 
that. The second method sees that we need member as a class and returns 
that. Note that simple type could mean anything, from int to bitmap image.

I have determined that this is possible if I sacrifice the final member 
reference to the __call__ override using function-call syntax: 1. x = 
obj.member(). The call syntax returns the simple value and the other returns 
the class. It is also possible if I override the __xxxitem__ methods to 
simulate a dictionary.

However, I would like to use the true member access syntax if possible.

So, is it possible?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fool Python class with imaginary members (serious guru stuff inside)

2012-09-20 Thread Terry Reedy

On 9/20/2012 9:52 AM, Jure Erznožnik wrote:

I'm trying to create a class that would lie to the user that a member is in 
some cases a simple variable and in other cases a class. The nature of the 
member would depend on call syntax like so:
1. x = obj.member #x becomes the simple value contained in member
2. x = obj.member.another_member #x becomes the simple value contained in 
first member's another_member.


x.y.z is parsed and executed as (x.y).z, so you are asking if the 
attribute-getter can know what will be done with the object it returns.
Assuming CPython, you would have to write something that searches the 
Python code before compilation, the ast during compilation, or the 
bytecode after compilation.


Much easier would be to define a union class that is a simple type with 
attributes and return that in the first lookup.


class AttrInt(int):
def __getattr__(self, name): return 'attribute'

y = AttrInt(3)
print(y, y.a)
###
3 attribute

If x.y returns an AttrInt, it will act like an int for most purposes, 
while x.y.z will return whatever AttrInt.__getattr__ does and the 
temporary AttrInt y disappears.


--
Terry Jan Reedy


--
http://mail.python.org/mailman/listinfo/python-list


Re: Fool Python class with imaginary members (serious guru stuff inside)

2012-09-20 Thread Steven D'Aprano
On Thu, 20 Sep 2012 06:52:07 -0700, Jure Erznožnik wrote:

 I'm trying to create a class that would lie to the user that a member is
 in some cases a simple variable and in other cases a class. The nature
 of the member would depend on call syntax like so: 
 1. x = obj.member #x becomes the simple value contained in member 
 2. x = obj.member.another_member #x becomes the simple value
 contained in first member's another_member.

Why do you hate your users so much that you want to cause them enormous 
difficulty with perfectly reasonable code like this?

tmp = obj.member
x = tmp.another_member


 So the first method detects that we only need a simple value and
 returns that.

Fortunately that is impossible without nasty bytecode or AST hacks. Thank 
the stars that Python doesn't allow anything as badly designed as this!



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A Python class

2012-09-06 Thread Terry Reedy

On 9/6/2012 11:08 AM, Yves S. Garret wrote:


I'd like to know if there are any online Python classes offered
online from reliable institutions that you would recommend.


Google 'online programming course python' for taught courses.
At least 2 of MIT's self-guided OpenCourseWare courses use Python.

http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-189-a-gentle-introduction-to-programming-using-python-january-iap-2011/

http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/

If you wanted to do one of those, you might find a partner by asking 
here. There might be a matchmaking site, but I could not find one.


--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: A Python class

2012-09-06 Thread Chris Angelico
On Fri, Sep 7, 2012 at 3:30 AM, Terry Reedy tjre...@udel.edu wrote:
 On 9/6/2012 11:08 AM, Yves S. Garret wrote:

 I'd like to know if there are any online Python classes offered
 online from reliable institutions that you would recommend.

 Google 'online programming course python' for taught courses.
 At least 2 of MIT's self-guided OpenCourseWare courses use Python.

Note this subtle distinction. A Python course will (theoretically, at
least!) teach you how to write Python code. A Python class is a
collection of methods and stuff. A trivial and petty distinction,
perhaps, but when you go searching the web, you'll get better results
with the right word.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Instantiate a python class object in C

2012-03-14 Thread Dids
Hi,

Apologies if this was asked before, I couldn't find anything.

I have a class defined in a python file:
for example:

class demo:
  [ class definition goes here]

I'm writing a C extension.
In the first function, I take an instance of the demo class and do
my magic. It's working, all is good.

What I can't figure out is how to create a second C function that
returns a new instance to the demo class to python.
There must a be tutorial somewhere, but I can't find anything. I do
not want to define a new python class in C.

Another example:
   This is working:
demo_obj1 = demo()
my_C_extension.function_1( demo_obj1 )  //working, all good.

   This I can't figure out how to do:
new_demo_obj = my_C_extension.function_2()

Thanks for reading,
Dids,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Instantiate a python class object in C

2012-03-14 Thread Stefan Behnel
Dids, 14.03.2012 14:46:
 Apologies if this was asked before, I couldn't find anything.
 
 I have a class defined in a python file:
 for example:
 
 class demo:
   [ class definition goes here]
 
 I'm writing a C extension.
 In the first function, I take an instance of the demo class and do
 my magic. It's working, all is good.
 
 What I can't figure out is how to create a second C function that
 returns a new instance to the demo class to python.
 There must a be tutorial somewhere, but I can't find anything. I do
 not want to define a new python class in C.
 
 Another example:
This is working:
 demo_obj1 = demo()
 my_C_extension.function_1( demo_obj1 )  //working, all good.
 
This I can't figure out how to do:
 new_demo_obj = my_C_extension.function_2()

You should consider giving Cython a try. It will allow you to write normal
Python code for your C extension that it translates to efficient C code.
This is much easier than writing all of this by hand, especially when it
comes to classes. It will also optimise the code for you, so that you'll
often end up with faster code than what you'd manually write.

Stefan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Instantiate a python class object in C

2012-03-14 Thread Dids
Ok, I have it :)

PyImport_Import , PyModule_GetDict, PyDict_GetItemString and
PyObject_CallObject

Need to take a second look at cython when I have a spare cycle or 2.

Thanks for the the tip :)

A+
Dids,

-- 
http://mail.python.org/mailman/listinfo/python-list


How to get python class serializable and well parsed by JSON

2011-03-11 Thread Arthur Mc Coy
Hi people,

I've created very nice post here:
http://stackoverflow.com/questions/5274690/how-to-get-python-class-serializable-and-well-parsed-by-json-custom-encoder-deco

Yes, there are solutions over the internet, but nothing works for my
custom types.
If you could answer, please read it.

Be happy!
Arthur
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get python class serializable and well parsed by JSON

2011-03-11 Thread Arthur Mc Coy
Common guys, help me, sweet heart to finish my job and go with my
friend in the bar. Today we have a blues night :) Love it!

Christina
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get python class serializable and well parsed by JSON

2011-03-11 Thread Arthur Mc Coy
Currently trying to pick up my ava http://en.gravatar.com/christinasanders21
for StackOverflow, which site I found very good for my questions,
didn't I?
Yes, and there are problem when adding a picture. Web admins should be
careful.
Can anyone explain me my problem ? :

Christina
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get python class serializable and well parsed by JSON

2011-03-11 Thread Sophie Sperner
Ok, guys. I used my bro account. Now I'm here. By the way is anybody
going to be in Paris Sunday night ?
I invite you if you would help :))) Kiss, well yet 30 minutes at work
and I'm free...

Sophie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get python class serializable and well parsed by JSON

2011-03-11 Thread Gennadiy Zlobin
I can not open your link. Are you sure you provided the correct link?


- Gennadiy gennad.zlo...@gmail.com


On Fri, Mar 11, 2011 at 10:36 PM, Arthur Mc Coy 1984docmc...@gmail.comwrote:

 Currently trying to pick up my ava
 http://en.gravatar.com/christinasanders21
 for StackOverflow, which site I found very good for my questions,
 didn't I?
 Yes, and there are problem when adding a picture. Web admins should be
 careful.
 Can anyone explain me my problem ? :

 Christina
 --
 http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


May Introduction to Python class

2010-04-27 Thread Steve Holden
Holden Web is pleased to announce the next run of its popular three-day
Introduction to Python class in Washington DC on May 11-13, 2010.

Further details of all current event listings are available from

  http://holdenweb.eventbrite.com/

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


May Introduction to Python class

2010-04-27 Thread Steve Holden
Holden Web is pleased to announce the next run of its popular three-day
Introduction to Python class in Washington DC on May 11-13, 2010.

Further details of all current event listings are available from

  http://holdenweb.eventbrite.com/

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


JSR223 Access Python class instances through Java

2009-11-12 Thread Jared Klumpp
I am trying to access (from Java) a python class that extends a Java
interface. The following program runs fine in the jython console (I
can instantiate Tada, call t.getName() and everything prints
correctly.) However, if I invoke test1() from Java using JSR223, the
returned object is inaccessible (proxy type) and none of the in
init, in getName strings will print.

Furthermore, none of the lines print unless I convert ITest to a
concrete class, but then the getName methods return the concrete
implementation's string.

Has anyone successfully had this situation work, and how did you do
it?

Thanks in advance

Code:
===
import ITest

class Tada(ITest):
def __init__(self):
print In Init

def getName(self):
print In getName
return Joe Schmoe


def test1():
t = Tada()
print t.getName()
print Hello, World
return t

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Storing a C pointer in a Python class instance

2009-10-06 Thread lallous
Carl Banks pavlovevide...@gmail.com wrote in message 
news:d50bba1e-b272-4e39-8a58-377531278...@z4g2000prh.googlegroups.com...

On Sep 30, 5:24 am, lallous lall...@lgwm.org wrote:

Hello

After using the PyCObject, I cannot pickle the class anymore.
Any simple solution to this problem? (or resorting to __reduce__ is the 
only

solution?)



You can't pickle a CObject, you'd have to create a custom type (one
that implements one of the pickling methods) for that.  Or arrange for
whatever object contains the CObject to pack and unpack it manually.

Out of curiosity, what kind of data you storing in this CObject?
Maybe we can help you choose a better way to handle it at the C level.




I am wrapping a C++ pointer with the python object. That way I can tell with 
which C++ object a given python class instance is associated.


The thing is when developing, I need to pickle but I don't need the C++ 
pointer, so I solved the problem with conditional compilation:

- testing: pickle allowed and This is stored in the py object
- production code: no need to pickle and this and pyobject are bound

Thanks,
Elias 


--
http://mail.python.org/mailman/listinfo/python-list


Re: Storing a C pointer in a Python class instance

2009-09-30 Thread lallous

Thanks everyone.

Finally, I used Falcolas suggestion and took into consideration 
sturlamolden's comments.


Regards,
Elias
lallous lall...@lgwm.org wrote in message news:h9sgcn$iv...@aioe.org...

Hello

From my C extension module I want to store a C pointer in a given 
PyObject.


The only way I figure how to do it is to use Py_BuildValues and store the 
poiner casted to Py_ssize_t, thus:


Py_BuildValues(n, (Py_ssize_t)my_ptr)

Can it be done differently?

Regards,
Elias 


--
http://mail.python.org/mailman/listinfo/python-list


Re: Storing a C pointer in a Python class instance

2009-09-30 Thread lallous

Hello

After using the PyCObject, I cannot pickle the class anymore.
Any simple solution to this problem? (or resorting to __reduce__ is the only 
solution?)


Thanks,
Elias

Falcolas garri...@gmail.com wrote in message 
news:9d3790aa-f7d9-4bb5-a81f-5428b2d60...@v25g2000yqk.googlegroups.com...

On Sep 29, 2:27 am, lallous lall...@lgwm.org wrote:

Hello

From my C extension module I want to store a C pointer in a given 
PyObject.


The only way I figure how to do it is to use Py_BuildValues and store the
poiner casted to Py_ssize_t, thus:

Py_BuildValues(n, (Py_ssize_t)my_ptr)

Can it be done differently?

Regards,
Elias


You can use a PyCObject_FromVoidPtr

http://docs.python.org/c-api/cobject.html

PyArg_ParseTuple(args, O, pyVoidPointer);
castPointer = (type *) PyCObject_AsVoidPtr(pyVoidPointer);
return PyCObject_FromVoidPtr((void *) castPointer, NULL); 


--
http://mail.python.org/mailman/listinfo/python-list


Re: Storing a C pointer in a Python class instance

2009-09-30 Thread Carl Banks
On Sep 30, 5:24 am, lallous lall...@lgwm.org wrote:
 Hello

 After using the PyCObject, I cannot pickle the class anymore.
 Any simple solution to this problem? (or resorting to __reduce__ is the only
 solution?)


You can't pickle a CObject, you'd have to create a custom type (one
that implements one of the pickling methods) for that.  Or arrange for
whatever object contains the CObject to pack and unpack it manually.

Out of curiosity, what kind of data you storing in this CObject?
Maybe we can help you choose a better way to handle it at the C level.


Carl Banks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Storing a C pointer in a Python class instance

2009-09-30 Thread Carl Banks
On Sep 29, 11:16 am, sturlamolden sturlamol...@yahoo.no wrote:
 On 29 Sep, 19:11, Carl Banks pavlovevide...@gmail.com wrote:

  CObjects can be passed a C function as a deallocator; this should work
  as reliably as a custom class deallocator.

 Except that __del__ prevents cyclic GC.

You are mistaken on two counts.

First of all, a CObject is not a container.  It can't prevent cyclic
GC because it's never a part of a cycle.

Second, CObjects do not have a __del__ method.  They call the supplied
constructor from the type's tp_dealloc slot.  Use of the tp_dealloc
slot does not, by itself, prevent cyclic GC.

Bottom line is, the CObject's deallocator is as reliable as a custom
type's tp_dealloc.


Carl Banks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Storing a C pointer in a Python class instance

2009-09-30 Thread sturlamolden
On 30 Sep, 19:03, Carl Banks pavlovevide...@gmail.com wrote:

 Second, CObjects do not have a __del__ method.  They call the supplied
 constructor from the type's tp_dealloc slot.  Use of the tp_dealloc
 slot does not, by itself, prevent cyclic GC.

 Bottom line is, the CObject's deallocator is as reliable as a custom
 type's tp_dealloc.

You are right. I did not look at the PyCObject_* API close enough.

I thought of wrapping the CObject with a Python class, and calling the
destructor from __del__. That would be less reliable.

S.M.






-- 
http://mail.python.org/mailman/listinfo/python-list


Storing a C pointer in a Python class instance

2009-09-29 Thread lallous

Hello


From my C extension module I want to store a C pointer in a given PyObject.


The only way I figure how to do it is to use Py_BuildValues and store the 
poiner casted to Py_ssize_t, thus:


Py_BuildValues(n, (Py_ssize_t)my_ptr)

Can it be done differently?

Regards,
Elias 


--
http://mail.python.org/mailman/listinfo/python-list


Re: Storing a C pointer in a Python class instance

2009-09-29 Thread Falcolas
On Sep 29, 2:27 am, lallous lall...@lgwm.org wrote:
 Hello

 From my C extension module I want to store a C pointer in a given PyObject.

 The only way I figure how to do it is to use Py_BuildValues and store the
 poiner casted to Py_ssize_t, thus:

 Py_BuildValues(n, (Py_ssize_t)my_ptr)

 Can it be done differently?

 Regards,
 Elias

You can use a PyCObject_FromVoidPtr

http://docs.python.org/c-api/cobject.html

PyArg_ParseTuple(args, O, pyVoidPointer);
castPointer = (type *) PyCObject_AsVoidPtr(pyVoidPointer);
return PyCObject_FromVoidPtr((void *) castPointer, NULL);
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Storing a C pointer in a Python class instance

2009-09-29 Thread sturlamolden
On 29 Sep, 10:27, lallous lall...@lgwm.org wrote:
 Hello

 From my C extension module I want to store a C pointer in a given PyObject.

 The only way I figure how to do it is to use Py_BuildValues and store the
 poiner casted to Py_ssize_t,

Formally, you should cast the pointer to Py_intptr_t, as it has the
same size as void*. Py_ssize_t has the same size as size_t, but the C
standard does not mandate that sizeof(void*) == sizeof(size_t). In
fact there are segment and offset architectures where this is not
true. Casting a pointer to Py_ssize_t accidentally works if you have a
flat address space.


 Can it be done differently?

You can use PyCObject, or write your own extension type that wraps the
pointer (very easy to to with Cython or Pyrex). The advantage of using
an extension type is you have a guarantee from Python on the
deallocator method being called (cdef __dealloc__ in Cython). If the
pointer references a resource that needs to be closed, this is safer
than using a __del__ method in a Python class.








-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Storing a C pointer in a Python class instance

2009-09-29 Thread Carl Banks
On Sep 29, 9:42 am, sturlamolden sturlamol...@yahoo.no wrote:
 You can use PyCObject, or write your own extension type that wraps the
 pointer (very easy to to with Cython or Pyrex). The advantage of using
 an extension type is you have a guarantee from Python on the
 deallocator method being called (cdef __dealloc__ in Cython).

CObjects can be passed a C function as a deallocator; this should work
as reliably as a custom class deallocator.


Carl Banks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Storing a C pointer in a Python class instance

2009-09-29 Thread sturlamolden
On 29 Sep, 19:11, Carl Banks pavlovevide...@gmail.com wrote:

 CObjects can be passed a C function as a deallocator; this should work
 as reliably as a custom class deallocator.

 Carl Banks

Except that __del__ prevents cyclic GC.

-- 
http://mail.python.org/mailman/listinfo/python-list


Visualization of Python Class Hierarchy

2009-07-16 Thread lh
I would like to automatically generate this for my program. I am
running python in  an eclipse context (pydev).  I am not familiar with
the best current tools.
 Thank you
-- 
http://mail.python.org/mailman/listinfo/python-list


Intro to Python class, 7/21-23, Ft Worth TX

2009-07-02 Thread Rich Drehoff
We are looking for someone that can help with the subject class, Intro to
Python class, 7/21-23, Ft Worth TX.  Please let me know if you can help.
Would need your resume and best possible daily rate.

 

Best regards,

 

Rich Drehoff

TechnoTraining, Inc.

328 Office Square Lane, Ste. 202, Virginia Beach, VA 23462-3648

(757) 425-0728 x15 / (757) 425-7323 Fax

Email: rdreh...@technotraining.net

Website: www.TechnoTraining.net http://www.technotraining.net/ 

 

-- 
http://mail.python.org/mailman/listinfo/python-list


Python class gotcha with scope?

2009-06-21 Thread billy
I don't quite understand why this happens. Why doesn't b have its own
version of r? If r was just an int instead of a dict, then it would.

 class foo:
... r = {}
... def setn(self, n):
... self.r[f] = n
...
 a = foo()
 a.setn(4)

 b = foo()
 b.r
{'f': 4}

thanks,

billy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python class gotcha with scope?

2009-06-21 Thread Vincent
On Jun 21, 2:32 pm, billy billy.cha...@gmail.com wrote:
 I don't quite understand why this happens. Why doesn't b have its own
 version of r? If r was just an int instead of a dict, then it would.

  class foo:

 ...     r = {}
 ...     def setn(self, n):
 ...             self.r[f] = n
 ... a = foo()
  a.setn(4)

  b = foo()
  b.r

 {'f': 4}

 thanks,

 billy


class Foo:
def __init__(self):
self.r = {}
def setn(self,n):
self.r['f'] = n

a = Foo()
a.setn(3)
a.r
{'f': 3}
b = Foo()
b.r
{}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python class gotcha with scope?

2009-06-21 Thread Vincent
On Jun 21, 2:38 pm, Vincent pho...@gmail.com wrote:
 On Jun 21, 2:32 pm, billy billy.cha...@gmail.com wrote:



  I don't quite understand why this happens. Why doesn't b have its own
  version of r? If r was just an int instead of a dict, then it would.

   class foo:

  ...     r = {}
  ...     def setn(self, n):
  ...             self.r[f] = n
  ... a = foo()
   a.setn(4)

   b = foo()
   b.r

  {'f': 4}

  thanks,

  billy

 class Foo:
     def __init__(self):
         self.r = {}
     def setn(self,n):
         self.r['f'] = n

 a = Foo()
 a.setn(3)
 a.r
 {'f': 3}
 b = Foo()
 b.r
 {}

you defined r as class-level variable.
and i defined r as instance-level variable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python class gotcha with scope?

2009-06-21 Thread Carl Banks
On Jun 20, 11:32 pm, billy billy.cha...@gmail.com wrote:
 I don't quite understand why this happens. Why doesn't b have its own
 version of r? If r was just an int instead of a dict, then it would.

  class foo:

 ...     r = {}
 ...     def setn(self, n):
 ...             self.r[f] = n
 ... a = foo()
  a.setn(4)

  b = foo()
  b.r

 {'f': 4}

r is a class attribute, that is, it is attacted to the class itself.
Look at what happens when you enter foo.r at the interactive prompt:

 foo.r
{'f': 4}


You want an instance attribute, a value attached to the instance of
the class.  You create those in the __init__ method:


class foo:
def __init__(self):
self.r = {}
def setn(self,n):
self.r[n] = n



Carl Banks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python class gotcha with scope?

2009-06-21 Thread billy
great, thanks for the quick responses :)


On Jun 21, 2:41 am, Carl Banks pavlovevide...@gmail.com wrote:
 On Jun 20, 11:32 pm, billy billy.cha...@gmail.com wrote:

  I don't quite understand why this happens. Why doesn't b have its own
  version of r? If r was just an int instead of a dict, then it would.

   class foo:

  ...     r = {}
  ...     def setn(self, n):
  ...             self.r[f] = n
  ... a = foo()
   a.setn(4)

   b = foo()
   b.r

  {'f': 4}

 r is a class attribute, that is, it is attacted to the class itself.
 Look at what happens when you enter foo.r at the interactive prompt:

  foo.r

 {'f': 4}

 You want an instance attribute, a value attached to the instance of
 the class.  You create those in the __init__ method:

 class foo:
     def __init__(self):
         self.r = {}
     def setn(self,n):
         self.r[n] = n

 Carl Banks

-- 
http://mail.python.org/mailman/listinfo/python-list


Introduction to Python Class, in Chicago, May 11-13, 2009.

2009-01-07 Thread David Beazley
David Beazley, author of the Python Essential Reference is pleased to
announce an Introduction to Python class on May 11-13, 2009 in
Chicago, Illinois.

This course, open to individual enrollment, is a comprehensive
hands-on course for programmers, scientists, and engineers who want to
master the essential elements of Python programming in order to solve
real-world problems in data processing, systems programming, and
software integration.  This is the same acclaimed course that Dave has
taught at more than 30 on-site locations in 2007-2008.  

The venue for this class is centrally located in the heart of
Chicago's downtown financial/theater district.  When the class is not
in session, you will be just steps away from many of Chicago's most
famous parks and cultural attractions.  So, come prepared for three
days of serious Python instruction and urban exploration.

More details about the class can be found at:

http://www.dabeaz.com/chicago

I hope to see you there!

--
Dave Beazley
http://www.dabeaz.com






--
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Final Python Class of 2008

2008-11-11 Thread Steve Holden
Steve Holden wrote:
 As the year draws to a close, Holden Web is pleased to remind readers
 that its final public Introduction to Python class of this year will
 be held from 9-11 December at our education center close to Washington, DC.
 
 There are several hotels conveniently located within walking distance,
 and we provide breakfast snacks on lunch each day.
 
 You can purchase places on-line at
 
   http://holdenweb.com/py/training/
 
 by credit card or using PayPal.
 
 Thanks to all students who have already attended this class. We look
 forward to meeting you again as our range of course offerings increases.

Since this is 2008, please understand that the former title was a typo
and we weren't advertising classes 12 months in advance ...

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

--
http://mail.python.org/mailman/listinfo/python-list


Re: Final Python Class of 2009

2008-11-11 Thread skip

 Steve, have you been in Guido's time machine again?

Steve No, honest (hides hands behind back).

Well then what's that red stuff on your face that looks like strawberry jam?
Could it be the special grease we store next to the keys to the time
machine?

Skip
--
http://mail.python.org/mailman/listinfo/python-list


Re: Final Python Class of 2009

2008-11-11 Thread Steve Holden
Steven D'Aprano wrote:
 On Mon, 10 Nov 2008 22:14:16 -0500, Steve Holden wrote:
 
 Subject: Final Python Class of 2009
 
 Steve, have you been in Guido's time machine again?
 
:-)
 
 
No, honest (hides hands behind back).

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

--
http://mail.python.org/mailman/listinfo/python-list


Re: Final Python Class of 2009

2008-11-11 Thread Steve Holden
[EMAIL PROTECTED] wrote:
  Steve, have you been in Guido's time machine again?
 
 Steve No, honest (hides hands behind back).
 
 Well then what's that red stuff on your face that looks like strawberry jam?
 Could it be the special grease we store next to the keys to the time
 machine?
 
[no answer]
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

--
http://mail.python.org/mailman/listinfo/python-list


Final Python Class of 2009

2008-11-10 Thread Steve Holden
As the year draws to a close, Holden Web is pleased to remind readers
that its final public Introduction to Python class of this year will
be held from 9-11 December at our education center close to Washington, DC.

There are several hotels conveniently located within walking distance,
and we provide breakfast snacks on lunch each day.

You can purchase places on-line at

  http://holdenweb.com/py/training/

by credit card or using PayPal.

Thanks to all students who have already attended this class. We look
forward to meeting you again as our range of course offerings increases.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

--
http://mail.python.org/mailman/listinfo/python-list


Re: Final Python Class of 2009

2008-11-10 Thread Steven D'Aprano
On Mon, 10 Nov 2008 22:14:16 -0500, Steve Holden wrote:

Subject: Final Python Class of 2009

Steve, have you been in Guido's time machine again?



-- 
Steven (not Steve Holden, another one)

--
http://mail.python.org/mailman/listinfo/python-list


2009 Python class schedule

2008-11-06 Thread Mark Lutz
A page describing our 2009 Python class offerings has just
been posted here:

http://home.earthlink.net/~python-training/2009-public-classes.htm

The first class in 2009 will be held January 27-30 in
Colorado, and is now open for enrollments.

These are public classes, open to individuals.  They provide
in-depth and hands-on introductions to Python and its common
applications, and are based upon the instructor's popular
Python books.

Thanks for your interest,
--Mark Lutz at Python Training
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python class questions

2008-06-20 Thread John Dann
Many thanks for the further comments:

On Thu, 19 Jun 2008 21:24:31 -0400, Terry Reedy [EMAIL PROTECTED]
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
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python class questions

2008-06-20 Thread cokofreedom

 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.

Without insulting your intelligence I would advise looking at a few
python tutorials, not so much for the programming technique, but
rather how to think pythonic. A good one for using when coming from a
previous programming language is
Dive Into Python. http://www.diveintopython.org/

It does not deal with Serial specifically, but shows good examples of
practises in Python. Might be of benefit to you, and is very easy and
quick to read. :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python class questions

2008-06-20 Thread Duncan Booth
John Dann [EMAIL PROTECTED] wrote:

 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.

Python starts executing at the top of your main script and then proceeds 
line by line down until it falls off the bottom. Various things can 
divert it from this straightforward progression towards the end of the 
script, some of them such as if/for/while/raise or function calls are 
obvious, but the less obvious ones include:

import somemodule (or 'from somemodule import something')

if 'somemodule' has not previously been imported this will find the 
module and execute the lines of code in the module from top to bottom 
just as for the main script. When it falls off the bottom of the module 
it returns to the import statement, assigns the module or the imported 
attributes to a name or names in the calling namespace (yes, an import 
is just a highly specialised assignment statement), and then continues 
with the next statement.

If somemodule has already started being imported anywhere in the program 
then the import simply returns immediately and does the assignment. 
(This can be a cause of confusion if you try to import modules 
recursively as it is perfectly possible that the imported module has not 
yet finished executing, so it may not yet have all the classes and 
functions you expect).

class somename(bases):
somecode

A 'class' statement in Python is just executable code. The body of the 
class is executed from top to bottom but in a new namespace. When 
execution falls off the bottom of the class body a new class object is 
created from that namespace and the base classes. The new class object 
is then assigned to 'somename' (i.e. a class statement is a specialised 
assignment statement). Then execution then procedes with the next 
statement.

def functionname(arg1, arg2=default):
somecode

A 'def' statement in Python is also a specialised assignment statement: 
unlike 'class' it doesn't immediately execute the code in the body, but 
it does evaluate any default argument values when it encounters the 
'def'. Then it creates a new function object from the code in the body 
and the default arguments (and a few other things such as the argument 
specification and the function name). Then it continues with the next 
statement.

global name

The 'global' statement is not executed at runtime. It is the only Python 
statement which is purely compile time.

Once you understand this it should be much clearer: everything except 
global is executed when it is encountered following the normal rules for 
program flow, and all the ways of creating module, classes, and 
functions simply execute some code and then do an assignment (and so if 
you wish you can later overwrite the values they assigned).

If you wish to do something special when an import fails then you simply 
put try:..except: around the import at the top level in a module and 
handle it there: you don't need to put either the import or the handler 
inside a function.

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python class questions

2008-06-20 Thread Lie
On Jun 19, 10:49 pm, Ulrich Eckhardt [EMAIL PROTECTED] wrote:
 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


I'm not sure how you think saying 'in comms.py I have:' is an explicit
declaration that it is the very code in his comms.py, on contrary, he
said: '...provide some outline code as an illustration: ', but let's
stop polluting this thread.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python class questions

2008-06-20 Thread David C. Ullrich
In article 
[EMAIL PROTECTED],
 Lie [EMAIL PROTECTED] wrote:

 On Jun 19, 7:21 pm, Ulrich Eckhardt [EMAIL PROTECTED] wrote:
  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.
 [...]
 
  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

I would have _thought_ it wasn't hard to see that if a person
says he's totally new to the language, and even explicitly says
that the problem could be syntax errors, then he shouldn't
post pseudo code. How in the world is pseudo code going to
allow people to help him fix his syntax?

-- 
David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list

Simple Python class questions

2008-06-19 Thread John Dann
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 misunderstanding 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.seral_link #Create instance of serial_link class
print serlink.openPort


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.openPort' 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
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python class questions

2008-06-19 Thread Cédric Lucantis
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.openPort


You just forgot the (), so you're printing the method object itself without 
calling it : print serlink.openPort()

-- 
Cédric Lucantis
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python class questions

2008-06-19 Thread Lie
On Jun 19, 6:54 pm, John Dann [EMAIL PROTECTED] wrote:
 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 misunderstanding 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.seral_link     #Create instance of serial_link class
 print serlink.openPort

 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.openPort' 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

--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python class questions

2008-06-19 Thread Ulrich Eckhardt
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

--
http://mail.python.org/mailman/listinfo/python-list

Re: Simple Python class questions

2008-06-19 Thread John Dann
Many thanks for the speedy replies.

On Thu, 19 Jun 2008 14:14:02 +0200, Cédric Lucantis [EMAIL PROTECTED]
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
[EMAIL PROTECTED] wrote:

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
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python class questions

2008-06-19 Thread Cédric Lucantis
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 [EMAIL PROTECTED]

 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
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python class questions

2008-06-19 Thread Lie
On Jun 19, 7:21 pm, Ulrich Eckhardt [EMAIL PROTECTED] wrote:
 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
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python class questions

2008-06-19 Thread Ulrich Eckhardt
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ührer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

--
http://mail.python.org/mailman/listinfo/python-list

Re: Simple Python class questions

2008-06-19 Thread Terry Reedy



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.seral_link


()

 #Create instance of serial_link class

print serlink.openPort


()

Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Class Best Practice

2007-12-12 Thread MarkE
On 4 Dec, 23:18, Rod Person [EMAIL PROTECTED] wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 I've been doing python programming for about 2 years as a hobby and now
 I'm finally able to use it at work in an enterprise environment. Since
 I will be creating the base classes and libraries I wondering which why
 is consider best when creating python classes:

 1:
 class Foo(object):
   member1=''
   member2=0

   def __init__(self,member1='',member2=0):
 self.member1 = member1
 self.member2 = member2

 2:
 class Foo(object):
 def  __init(self,member1='',member2=0):
 self.member1 = member1
 self.member2 = member2


Don't forget to call the base class __init__ function
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Class Best Practice

2007-12-07 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 On Dec 5, 12:18 am, Rod Person [EMAIL PROTECTED] wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 I've been doing python programming for about 2 years as a hobby and now
 I'm finally able to use it at work in an enterprise environment. Since
 I will be creating the base classes and libraries I wondering which why
 is consider best when creating python classes:

 1:
 class Foo(object):
   member1=''
   member2=0

   def __init__(self,member1='',member2=0):
 self.member1 = member1
 self.member2 = member2

 2:
 class Foo(object):
 def  __init(self,member1='',member2=0):
 self.member1 = member1
 self.member2 = member2

 
 
 The short answer : if 2 works, then stick with it.

The yet-even-shorter-answer: 2

!-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Class Best Practice

2007-12-05 Thread cptnwillard
On Dec 5, 12:18 am, Rod Person [EMAIL PROTECTED] wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 I've been doing python programming for about 2 years as a hobby and now
 I'm finally able to use it at work in an enterprise environment. Since
 I will be creating the base classes and libraries I wondering which why
 is consider best when creating python classes:

 1:
 class Foo(object):
   member1=''
   member2=0

   def __init__(self,member1='',member2=0):
 self.member1 = member1
 self.member2 = member2

 2:
 class Foo(object):
 def  __init(self,member1='',member2=0):
 self.member1 = member1
 self.member2 = member2



The short answer : if 2 works, then stick with it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Class Best Practice

2007-12-04 Thread Rod Person
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

I've been doing python programming for about 2 years as a hobby and now
I'm finally able to use it at work in an enterprise environment. Since
I will be creating the base classes and libraries I wondering which why
is consider best when creating python classes:

1:
class Foo(object):
  member1=''
  member2=0
 
  def __init__(self,member1='',member2=0):
self.member1 = member1
self.member2 = member2

2:
class Foo(object):
def  __init(self,member1='',member2=0):
self.member1 = member1
self.member2 = member2


- -- 
Rod
http://roddierod.homeunix.net:8080
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.7 (FreeBSD)

iD8DBQFHVeAscZAIaGStcnARAhRnAKCNFfjStOPGs/9tMI6bKuBQTPiJHQCdEMdY
OQPSSZlJWqkLxZvPwI2ctVs=
=CfvK
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Class Best Practice

2007-12-04 Thread Gary Herron
Rod Person wrote:
 I've been doing python programming for about 2 years as a hobby and now
 I'm finally able to use it at work in an enterprise environment. Since
 I will be creating the base classes and libraries I wondering which why
 is consider best when creating python classes:

 1:
 class Foo(object):
   member1=''
   member2=0
  
   def __init__(self,member1='',member2=0):
 self.member1 = member1
 self.member2 = member2

 2:
 class Foo(object):
 def  __init__(self,member1='',member2=0):
 self.member1 = member1
 self.member2 = member2


Both examples will store values for member1 and member2 in every
instance.  Any code that accesses self.member1 (or 2) will get the value
stored in the instance. 

Example 1 which also creates two *class* members of the same name won't
affect the conclusion of the previous paragraph.  The two values in the
class will be shadowed by each instances members of the same name.

But now I need to ask, what did you expect to happen here? 

 * If you thought those two extra assignments in example 1 effected the
execution or storage in the __init__ (or any other method), you were
mistaken.

 * If you really wanted class members (i.e., values shared by ALL
instances), then they really shouldn't have the same name as instance
members.  You would surely confuse them at some point.

 * If you *really* wanted two class members *AND* two instance members
with the same names, (WHY???) then example 1 will do so, but you'll have
to access the instance members as self.member1 and the class members as
Foo.member1. 

Gary Herron

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Class Best Practice

2007-12-04 Thread Rod Person
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On Tue, 04 Dec 2007 15:51:18 -0800
Gary Herron [EMAIL PROTECTED] wrote:
 Rod Person wrote:
 
  1:
  class Foo(object):
member1=''
member2=0
   
def __init__(self,member1='',member2=0):
  self.member1 = member1
  self.member2 = member2
 
  2:
  class Foo(object):
  def  __init__(self,member1='',member2=0):
  self.member1 = member1
  self.member2 = member2
 
 
 Both examples will store values for member1 and member2 in every
 instance.  Any code that accesses self.member1 (or 2) will get the
 value stored in the instance. 
 
 Example 1 which also creates two *class* members of the same name
 won't affect the conclusion of the previous paragraph.  The two
 values in the class will be shadowed by each instances members of the
 same name.
 
 But now I need to ask, what did you expect to happen here? 

Well I guess I should say that I'm coming to Python from Delphi, so I
am used to creating classes like in #1, but I'm used to having to
declare a scope for each member. Not having a scope declaration is
really throwing me some.

 
  * If you thought those two extra assignments in example 1 effected
 the execution or storage in the __init__ (or any other method), you
 were mistaken.
 

Yes, this is what I thought. I thought that declaring member1='' would
just assign the a default value on creation of the class (as in
Delphi). I probably shouldn't have give the parameters in the __init__
a default value in example 1.

 Gary Herron

Thanks. 


- -- 
Rod

http://roddierod.homeunix.net:8080
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.7 (FreeBSD)

iD8DBQFHVeuucZAIaGStcnARAgEKAJ4/bJW9GSNTsmSgyOTokbCkEQFO7ACdErME
50Mgzge48M2z+nymifkByqo=
=e3gV
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Class Best Practice

2007-12-04 Thread Pavan Mishra
On Dec 5, 4:18 am, Rod Person [EMAIL PROTECTED] wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 I've been doing python programming for about 2 years as a hobby and now
 I'm finally able to use it at work in an enterprise environment. Since
 I will be creating the base classes and libraries I wondering which why
 is consider best when creating python classes:

 1:
 class Foo(object):
   member1=''
   member2=0

   def __init__(self,member1='',member2=0):
 self.member1 = member1
 self.member2 = member2

 2:
 class Foo(object):
 def  __init(self,member1='',member2=0):
 self.member1 = member1
 self.member2 = member2

 - --
 Rodhttp://roddierod.homeunix.net:8080
 -BEGIN PGP SIGNATURE-
 Version: GnuPG v1.4.7 (FreeBSD)

 iD8DBQFHVeAscZAIaGStcnARAhRnAKCNFfjStOPGs/9tMI6bKuBQTPiJHQCdEMdY
 OQPSSZlJWqkLxZvPwI2ctVs=
 =CfvK
 -END PGP SIGNATURE-

It depends on what we try to achieve.

The first definition gets me class defined with two class and instance
variables of the names member1 and member2. Where as second definition
gets class with only instance variables member1 and member2.

Both the definitions would allow me, Foo().member1 and Foo().member2.
Where as first definition would also allow me Foo.member1 and
Foo.member2.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >