2019独角兽企业重金招聘Python工程师标准>>>
class Point
VERSION = 2
@@num = 12
attr_accessor :x, :y
def initialize(x, y)
@x, @y = x, y
end
# 1 返回布尔值的方法末位一定要加上?
# 2 此处的x 与 y 是self.x 的省略写法, 因为有get 方法所以才可以这么写
# 当然也可以@x @y 这样的写法
def first_quadrant?
x > 0 && y > 0
end
# 3 但是在给局部变量赋值的时候一定不能简写成 x +=
def plus(a, b)
self.x += a
@y += b
end
# 4 符号方法
# 5 会自动将最后处理出来的结果return出去 此处省略return
# 6 此处的x 和 y 就是省略了self.x 或者@x 这种写法
def +(p2)
Point.new(@x + p2.x, @y + p2.y)
end
# 7 此处x 前面不能加self 此处的self指的是类
def self.second_quadrant?(x , y)
x < 0 && y > 0
# self指代的是类
# print self.xxxx
end
# 8 类方法可以合并成多个写法
class << self
def foo2
end
def bar2
end
end
end
# 9 实例无法调用类方法
# 10 类也无法直接调用实例方法
class Point
# 9 通过类直接调用全局变量 需要给类加一个方法
# 10 在ruby中可以直接打开类增加你需要的东西
def self.get_num
@@num
end
end
# 11 调用常量
# Point::VERSION
# 12 继承
class Point3D < Point
# 13 super调用父类的同名方法
def initialize(x, y, z)
super(x, y)
@z = z
end
end
class Point2D < Point
# 14 super如果不写参数的话 默认传入所有的参数给super
def initialize(x, y)
super
end
end
# 15 在Ruby中子类可以继承父类的所有方法 不管是private protected public
# 在Ruby子类可以重写如 父类的private 方法但不建议这么做
# 继承最好使用protected 和 public 方法
class Point
def prv_method
print 'this is private method'
end
private :prv_method
def pro_metod
print 'this is protected method'
end
protected :pro_metod
def wat
prv_method
pro_metod
end
def wut
# 16 private 方法和 protected最大的区别 private方法不能使用实例调用
# 只能隐式调用 所以self.prv_method 方法是错误的
# self.prv_method
self.pro_metod
end
end
# 17 is_a? 和 instance_of 的区别
p3 = Point3D.new(1, 2, 3)
# 18 is_a? 只要是这个类的实例或者是子类的实例都可
p p3.is_a?(Point)
p p3.instance_of?(Point3D)
# 19 instance_of? 只能是这个类的实例才可以
p p3.instance_of?(Point)
p p3.instance_of?(Point3D)
# 20 = - p3等于上个计算式的结果
# p1 = Point(2, 3)
# p2 = Point(3, 4)
# p1 + p2
# p3 = -