class problem, NoneType obj has no attribute

J. Cliff Dyer jcd at sdf.lonestar.org
Fri May 16 09:41:06 EDT 2008


On Fri, 2008-05-16 at 06:07 -0700, globalrev wrote:
> On 16 Maj, 14:19, Bruno Desthuilliers <bruno.
> 42.desthuilli... at websiteburo.invalid> wrote:
> > globalrev a écrit :
> >
> > > wassup here?
> >
> > > 7
> >
> > > Traceback (most recent call last):
> > >   File "C:\Python25\myPrograms\netflix\netflix.py", line 22, in
> > > <module>
> > >     print cust1.getID()
> > > AttributeError: 'NoneType' object has no attribute 'getID'
> >
> > > class customer:
> >
> > 1/ naming convention : class names should be CamelCased
> > 2/ unless you need compatibility with years old Python versions, use
> > newstyle classes
> >
> > class Customer(object):
> >
> > >     def __init__(self, ID, movies):
> > >         self.ID = ID
> > >         self.movies = movies
> >
> > 3/ naming conventions : ALL_UPPER_NAMES denote (pseudo) constants
> >
> >      def __init__(self, id, movies):
> >          self.id = id
> >          self.movies = movies
> >
> > >     def getID():
> > >         return self.ID
> >
> > >     def getMovies():
> > >         return self.movies
> >
> > 4/ Python has support for computed attributes, so you just don't need
> > these getters.
> >
> >
> >
> > > import os
> > > import customer
> > > import movie
> >
> > > mv1 = open('C:\\Python25\\myPrograms\\netflix\\mv1exp2.txt', 'r+')
> > > mv1str = mv1.read()
> >
> > > print mv1str.count(',5,')
> >
> > > cust1 = customer.__init__('12',['1','435','2332'])
> >
> > __init__ is automagically called on instanciation, so you don't have to
> > call it yourself. And FWIW, your __init__ returns None.
> >
> > cust1 = Customer('12', ['1', '435', '2332'])
> >
> > > print cust1.getID()
> >
> > print cust1.id
> 
> 
> what should init return normally? a customer-object?
> 
> class customer:
>     def __init__(self, idnbr, movies):
>         self.idnbr = idnbr
>         self.movies = movies
>         return self
> 
> 
> ?

No.  __init__ should not return anything (rather, it should return None,
but it'll do that on its own without you telling it to return anything).
The problem is that you are trying to create an object with __init__,
but that is not what it does.  It *initializes* objects that already
exist.  when you call a class, it creates a new instance using
__new__(), and then initializes it using __init__().  So if you were
really inclined to muck around.  You could do something like

cust1 = Customer.__new__(Customer)
cust1.__init__('12', ['1','435', '2332'])

But that would just be silly.  What you really want is this:

cust1 = Customer('12', ['1','435', '2332'])

which does the same thing.  Don't explicitly call under-under variables
unless you really have to.

Cheers,
Cliff






More information about the Python-list mailing list