python classes

William D. Gill wmgill at gcgroup.net
Thu Mar 4 12:48:07 EST 2004


"Peter Otten" <__peter__ at web.de> wrote in message
news:c27mrt$kge$03$1 at news.t-online.com...
> William D. Gill wrote:
>
> > I'm new to python and am probably trying too many new things at once,
but
> > here goes.
>
> Welcome!
>
> > I am working with a (MySQL) database and am trying to make a html
/python
> > interface for editing records.
> > Data is broken up into several tables, and related by customer number.
> > For example one table contains basic information about the customer, one
> > table phone numbers (one record for published number, one for cell
phone,
> > etc, all customers will have at least one record here).
> >
> > I want to use python classes in my code so I have a couple of  questions
> > about python classes:
> >
> > 1) can a class __init__ have multiple "signatures like in C++  i.e.
> > MyClass( int, string), . MyClass(int) ?
>
> No, but you can provide defaults:
>
> >>> class MyClass:
> ...     def __init__(self, mandatory, value=99, name="unknown"): pass
> ...
> >>> MyClass(1)
> <__main__.MyClass instance at 0x40290aec>
> >>> MyClass(1,2)
> <__main__.MyClass instance at 0x40290a6c>
> >>> MyClass(1, name="whoever")
> <__main__.MyClass instance at 0x40290a4c>
>
> and so on ad infinitum.
I'm not sure defaults do what I want.  In C++ I could create an instance
passing customer id , or the name, have the constructor interrogat the db
and create the same resulting object.
I could use default  id = None, name  = None, and have the constructor
either name, id , or a "no info given" to determine how to create the
object.

> > 2) can a class attribute be an instance of another class ...
>
> Yes, it can.
>
> > or is multiple inheritance the proper answer?
>
> If the _question_ is 42?, then I would say so :-)

the _question_ is:
which of the following is correct?

class MyClass:
    def __init__(self, id=0000):
        self.data = MyOtherClass(id)    # data is an object with name, id
and other properties

or

class MyClass(MyOtherClass)
    def __init__(self, id=0000):
         #self.data.id, self.data.name, and other properties are defined in
MyOtherClass and inherited in  MyClass

> > 3) Can I make instantiation fail if an invalid customer number is use,
and
> > wrap the "a=MyClass(cusid=999) in an exception?
>
> You _should_ raise a custom exception (just derive from Exception) which
can
> be loaded with arbitrary information - in your example that would rather
be
> the bad customer id than the inconsistant MyClass instance.

I'm not sure I understand?  I don't want python to create an instance if
given invalid data (i.e given an invalid id the db lookup will fail), and I
want to raise an exception when this happens.






More information about the Python-list mailing list