python classes
Peter Otten
__peter__ at web.de
Thu Mar 4 11:52:13 EST 2004
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.
> 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 :-)
> 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.
Peter
More information about the Python-list
mailing list