Methods

Python

  1. from __future__ import division
  2. from math import sqrt
  3.  
  4.  
  5. class Point(object):
  6. def __init__(self, x, y):
  7. self.x = x
  8. self.y = y
  9.  
  10. def distance(self, other):
  11. return sqrt(self.x * other.x + self.y * other.y)
  12.  
  13.  
  14. p1 = Point(1, 3)
  15. p2 = Point(2, 4)
  16. print p1.distance(p2) # 3.74165738677
  17. print p2.distance(p1) # 3.74165738677

Go

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "math"
  6. )
  7.  
  8. type Point struct {
  9. x float64
  10. y float64
  11. }
  12.  
  13. func (this Point) distance(other Point) float64 {
  14. return math.Sqrt(this.x*other.x + this.y*other.y)
  15. }
  16.  
  17. // Dince structs get automatically copied,
  18. // it's better to pass it as pointer.
  19. func (this *Point) distance_better(other *Point) float64 {
  20. return math.Sqrt(this.x*other.x + this.y*other.y)
  21. }
  22.  
  23. func main() {
  24. p1 := Point{1, 3}
  25. p2 := Point{2, 4}
  26. fmt.Println(p1.distance(p2)) // 3.7416573867739413
  27. fmt.Println(p1.distance_better(&p2)) // 3.7416573867739413
  28. }