python classes

Peter Otten __peter__ at web.de
Thu Mar 4 13:37:19 EST 2004


William D. Gill wrote:

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

That's exactly what I'd do. An alternative would be to use factory functions
(which could be static or class methods), e. g.

class Customer:
    def __init__(self, **kw):
        self.__dict__.update(kw)
    def fromId(id):
        # look up data in db
        if notFound:
            raise InvalidCustomer(id)
        return Customer(...)
    fromId = staticmethod(fromId)
    def fromName(name):
        # look up data in db
        return Customer(...)
    fromName = staticmethod(fromName)
 
> 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

I think this is an extra complication that gains you nothing. The only
exception would be that data would not be initialized in MyClass.__init__()
but lazily at some later point, a usefull pattern if for a significant part
of the MyClass instances you can get away with not initializing data at
all. You would then change MyClass as follows:

MyClass(object):
    def __init__(self, id):
        self.id = id
        self._data = None
    def getdata(self):
        if not self._data:
            self._data = MyOtherClass(self.id)
        return self._data
    data = property(getdata)


> 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

>From what you've shown so far it's not clear to me why you need MyOtherClass
at all. In Python, attributes come at practically no cost, just say, e. g.
myClass.departmentId = 1234. Therefore inheritance would only be useful if
you want to reuse methods. Just think of Python classes as if they
inherited from an infinite number of abstract base classes. A simple
example: in most cases you can replace a file instance with any object that
provides a write(str) method.

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

I suppose that was a mutual misunderstanding. Did you mean this by
"wrapping"?

try:
    customer = Customer.fromId(1234)
except InvalidCustomer, e:
    print e

That's fine with me (I read wrapping as making the Customer instance an
attribute of the exception)


Peter




More information about the Python-list mailing list