[Python-talk] Initializing a class...

Kent Johnson kent37 at tds.net
Wed Sep 2 17:39:06 EDT 2009


On Wed, Sep 2, 2009 at 3:38 PM, <bruce.labitt at autoliv.com> wrote:
> One thing that I have stumbled upon is that an instance of a class I
> created is not being initialized as I expected.  I thought (and apparently
> I was wrong -- what a surprise...) that merely creating an instance of it
> was enough.
>
> So how does one do this?
>
> class myVars:

BTW
  class myVars(object):
is preferred these days.

>        def __init__(self):
>                self.bufsize = 32
>                self.bufdat = zeros(32)
>                self.fftsize = 1
>                self.oldfftsize = 0
>                self.fftinput = zeros(self.fftsize)
> +1j*zeros(self.fftsize)
>                self.fftoutput = zeros(self.fftsize) +
> 1j*zeros(self.fftsize)
>                self.dt = 1.0e-13
>
>        def othermethods:
>
> I thought just doing the following was sufficient:
>
> c = myVars()
> print 'FFT initial data is', c.fftinput
>
> But I get AttributeError: myVars instance has no attribute 'fftinput'
>
> Where am I going astray?  How do I init c?

Your code looks right to me. For example:
In [1]: class MyVars:
   ...:     def __init__(self):
   ...:         self.fftinput = 3

In [8]: c = MyVars()

In [9]: c.fftinput
Out[9]: 3

Presumably your real code is not so simple? Is it possible you
redefined c or myVars somewhere? Try printing dir(c) and type(c) for
clues.

Kent


More information about the Python-talk mailing list