为什么从' class '类对象实例化对象时,方法的总数从81个减少到46个?
下面是我正在运行的代码:
class Automobile
def wheels(wheel)
puts "#{wheel}"
end
end
class Car < Automobile
def gears
puts "Automatic Transmission"
end
end
limo = Car.new
benz = Automobile.new
puts Automobile.methods.count
puts Car.methods.count
puts benz.methods.count
puts limo.methods.count
我猜子类没有继承某些方法,我认为它们是类方法,所以我做了一些测试,实现了"put Anyclass"显示的方法。"方法"不是类方法。必须是实例方法。
如何在Ruby中实现,以阻止子类继承某些方法?
你的整个问题似乎是基于一个错误的信念,即Car.methods
的结果不是Car类的类方法,而是它的实例方法。Car.methods
的结果是Car类本身的方法列表。要获得实例方法,您必须编写Car.instance_methods
。这就是为什么实例的方法比类的方法少。
对于我来说,下面是运行代码的结果:
puts Automobile.methods.count
#=> 95
puts Car.methods.count
#=> 95 (exactly as you'd expect, since it didn't define any new class methods)
puts benz.methods.count
#=> 57 (this is 1 more than the result of Object.instance_methods.count, since you added #wheels)
puts limo.methods.count
#=> 58 (1 more than benz.methods.count, since you added #gears)