gpt4 book ai didi

ruby - 继承中类方法的 self 与类名

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:02 27 4
gpt4 key购买 nike

在这段代码中:

class Dog
def self.bark
print "woof"
end
end

class Little_dog < Dog
end

Little_dog.bark

该方法继承自引用self 的通用类。但是下一段代码:

class Dog
def Dog.bark
print "woof"
end
end

class Little_dog < Dog
end

Little_dog.bark

也有效。我期待它给我一个错误,但它没有。

self如何引用类继承下的类方法?为什么在第二个例子中little_dog类有一个类方法bark,而我只将它定义为Dog的类方法?

最佳答案

self 广泛用于 Ruby Metaprogramming .

来自 Metaprogramming Ruby书:

Every line of Ruby code is executed inside an object—the so–called current object. The current object is also known as self, because you can access it with the self keyword.

Only one object can take the role of self at a given time, but no object holds that role for a long time. In particular, when you call a method, the receiver becomes self. From that moment on, all instance variables are instance variables of self, and all methods called without an explicit receiver are called on self. As soon as your code explicitly calls a method on some other object, that other object becomes self.

所以,在代码中:

class Dog
# self represents the class object i.e: Dog. Which is an instance of Class.
# `bark` will be treated as class method
def self.bark
print "woof"
end
end

也可以写成:

class Dog
# Dog is an instance of Class.
# `bark` will be treated as class method
def Dog.bark
print "woof"
end
end

继承允许子类使用其父类的特性。这就是为什么你可以在 Little_dog 类中访问 bark 方法,因为它继承了 Dog 类:

class Little_dog < Dog
# has `bark` as a class method because of Dog
end

Ruby style guide tip : 在 Ruby 中,使用 CamelCase 约定命名类和模块被认为是最佳实践。

关于ruby - 继承中类方法的 self 与类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26439251/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com