Can you set a class instance's attributes to zero by setting the instance to zero?

G

Gerard Flanagan

Hello

If I have the Vector class below, is there a means by which I can have
the following behaviour

(0, 0)

If there is such a means, will it still work with the __slots__
attribution uncommented?

Thanks

class Vector(object):

#__slots__ = ('x', 'y')

def __init__(self, a=0, b=0 ):
self.x = a
self.y = b

def __repr__(self):
return '(%s, %s)' % (self.x, self.y)
 
D

Diez B. Roggisch

Gerard said:
Hello

If I have the Vector class below, is there a means by which I can have
the following behaviour




(1, 2)


(0, 0)

If there is such a means, will it still work with the __slots__
attribution uncommented?

No, you can't. The reason is that python doesn't have an assignment
operator as e.g. C++ has. The "=" just binds the name A to some object -
without the object knowing it.

What's wrong with

class A:
def clear():
pass
...

A.clear()

? Alternatively, you could try and abuse one of the seldom used in-place
operator like __ior__:

A |= 0

But I wouldn't recommend that.

Regards,

Diez
 
T

Terry Hancock

If I have the Vector class below, is there a means by
which I can have the following behaviour


(0, 0)

As has already been mentioned, "A = 0" rebinds the name "A"
to the object "0" so there's no way it can mutate the object
A.

However, you could create an object "Origin" to use as a
vector zero:

Origin = Vector(0,0)

Or if you want to be shorter, more poetic, and make future
maintainers curse you, you can call it "O":

O = Vector(0,0)

;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top