frazman
frazman

Reputation: 33293

class in python with method acting on self. inheritance

I guess it would be easy for me to explain the question with an examply Suppose I want to write my own vector class. And in that class let say i want to define a method to add 2 vectors something like:

class vector:
.....
def add(self,other):
    ----some code

so basically what this will do is.. if a vector is vec then

vec.add(othervec)

will do the addition.. but how do i do this.. its like inherting your own class..datatype ? Thanks

Upvotes: 0

Views: 142

Answers (3)

uncreative
uncreative

Reputation: 1446

sure, you can do exactly as you said, suppose you are wanting to add / change functionality of list

class Vector(list):

    def add(self, v):
        list.extend(self, v)

and you can use it like this:

> v = Vector([1,2,3])
> v.add([4,5,6])
> print v
> [1, 2, 3, 4, 5, 6]

Upvotes: 1

phihag
phihag

Reputation: 288260

In Python, you should use duck typing, i.e. not worry about the type at all:

class Vector(object):
  def __init__(self, x, y):
    self.x = x
    self.y = y
  def add(self, othervec):
    return Vector(self.x + othervec.x, self.y + othervec.y)

If you want, you can make add modify the Vector object instead of returning a new one. However, that makes your class mutable and therefore harder to deal with:

  def add_mutable(self, othervec):
    self.x += othervec.x
    self.y += othervec.y

Upvotes: 2

Blender
Blender

Reputation: 298532

If you want to add two classes, I'd look at the __add__ function, which allows you to do normal addition (and not call .add()):

a + b

As for your question, I'm not exactly sure about what you're asking. I wrote my Vector() class like this:

class Vector:
  def __init__(self, x = 0, y = 0, z = 0):
    self.x = x
    self.y = y
    self.z = z

  def __add__(self, other):
    return Vector(self.x + other.x, self.y + other.y, self.z + other.z)

Upvotes: 3

Related Questions