Zac*_*ith 3 ruby inheritance class-method
在此代码中:
class Dog
def self.bark
print "woof"
end
end
class Little_dog < Dog
end
Little_dog.bark
Run Code Online (Sandbox Code Playgroud)
该方法继承自引用 的通用类self。但是下一个代码补丁:
class Dog
def Dog.bark
print "woof"
end
end
class Little_dog < Dog
end
Little_dog.bark
Run Code Online (Sandbox Code Playgroud)
也有效。我原以为它会给我一个错误,但它没有。
类继承下如何self引用类方法?为什么在第二个示例中该类little_dog有一个类方法bark,而我只将其定义为 的类方法Dog?
self广泛应用于Ruby 元编程。
来自《Ruby 元编程》一书:
\n\n\n\n\n每行 Ruby 代码都在一个对象\xe2\x80\x94 中执行,该对象\xe2\x80\x93 称为当前对象。当前对象也称为 self,因为您可以使用 self 关键字访问它。
\n\n在给定时间只有一个对象可以充当 self 的角色,但没有对象可以长时间保持该角色。特别是,当您调用\n方法时,接收者变成了 self。从那时起,所有实例变量都是 self 的实例变量,并且在没有显式接收者的情况下调用的所有方法都在 self 上调用。一旦您的代码显式调用某个其他对象上的方法,该其他对象就会成为 self。
\n
所以,在代码中:
\n\nclass Dog\n # self represents the class object i.e: Dog. Which is an instance of Class.\n # `bark` will be treated as class method\n def self.bark \n print "woof"\n end\nend\nRun Code Online (Sandbox Code Playgroud)\n\n也可以写成:
\n\nclass Dog\n # Dog is an instance of Class.\n # `bark` will be treated as class method\n def Dog.bark \n print "woof"\n end\nend\nRun Code Online (Sandbox Code Playgroud)\n\n继承允许子类使用其父类的功能。这就是为什么您可以访问类bark中的方法Little_dog,因为它是继承Dog类:
class Little_dog < Dog\n # has `bark` as a class method because of Dog\nend\nRun Code Online (Sandbox Code Playgroud)\n\nRuby 风格指南提示:在 Ruby 中,使用 CamelCase 约定来命名类和模块被认为是最佳实践。
\n