0

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

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Cool.. This works :) Or I think this will also work.. if we declare class as class Vector(object): ?? right??
Sure. As long as the object has .x, .y, and .z properties, this should work fine.
2

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

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.