Contents
18. Methods(方法)¶
18.1. Python¶
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2020/4/21 13:50
# filename: sample1.py
from __future__ import division
from math import sqrt
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
return sqrt(self.x * other.x + self.y * other.y)
p1 = Point(1, 3)
p2 = Point(2, 4)
print(p1.distance(p2)) # 3.74165738677
print(p2.distance(p1)) # 3.74165738677
18.2. Go¶
package main
import (
"fmt"
"math"
)
type Point struct {
x float64
y float64
}
func (this Point) distance(other Point) float64 {
return math.Sqrt(this.x*other.x + this.y*other.y)
}
// Dince结构会自动复制,
//最好将其作为指针传递。
func (this *Point) distance_better(other *Point) float64 {
return math.Sqrt(this.x*other.x + this.y*other.y)
}
func main() {
p1 := Point{
x: 1,
y: 3,
}
p2 := Point{
x: 2,
y: 4,
}
fmt.Println(p1.distance(p2)) //3.7416573867739413
fmt.Println(p1.distance_better(&p2)) //3.7416573867739413
}