initialize a class

Joe Mason joe at notcharles.ca
Sat Mar 27 21:10:30 EST 2004


In article <mailman.3.1080431006.20120.python-list at python.org>, myang wrote:
> Hi,
> 
> I am trying to construct a 'point' instance with two different methods (see
> the following codes). Why the second one can't work? It's strange, since
> 'self' refers to the newly created object, and the '=' assign a initialized
> instance to it.
> 
>>>> class Point:
> ... 	x = 0.0
> ... 	y = 0.0
> ...
>>>> def initializePoint(a,b):
> ... 	p = Point()
> ... 	p.x = a
> ... 	p.y = b
> ... 	return p
> ...
>>>> class Ppoint(Point):
> ... 	def __init__(self,a,b):
> ... 		self = initializePoint(a,b)

By the time it calls __init__, the Ppoint object is already created, and
a reference to it is passed in to the function in the self parameter.
What your code does is calls initializePoint, which creates a second
object, and stores a reference to *that* in self.  Then it throws it
away, since self is returned.  The original Ppoint object isn't touched.

The standard way to write an initializer is this:

    class Point:
        def __init__(self, a = 0.0, b = 0.0):
            self.x = a
            self.y = b

    def initializePoint(a, b):
        p = Point(a, b)
        return p

Since __init__ has default values, ig you just call Point(), you get 0.0
as before.  But now initializePoint() isn't very useful, and only exists
to keep your old code working.

> Acutally, what I want to do is like the code above: I have a huge class in a
> module, and a function to initialize instances of this class. But I want the
> instance of the class to be initialized when it's created. How can I fulfill
> such a task? Thanks!

If you're allowed to change the class, just move initializeC to
C.__init__, as above.

If you're not allowed to change the Point class, but you can change the
initialize function, you can do this:

    class Point:
        x = 0.0
        y = 0.0

    def __initializePoint(p, a, b):
        p.x = a
        p.y = b

    def initializePoint(a, b):
        p = Point()
        __initializePoint(p, a, b)
        return p

    class Ppoint(Point):
        def __init__(self, a, b):
            __initializePoint(self, a, b)

Now the two ways to create a point (Ppoint() and initializePoint()) both
create an object, then call the same initiailzation code.

If you can't change any of the code from the module, it's more complex.
Complain to whoever wrote it - why on Earth did they design it that way?

Joe



More information about the Python-list mailing list