在Programming Ruby中,我看到一个类方法被定义为
class File
def self.my_open(*args)
#...
end
end
前缀“self.”是什么意思?是指这里?
最佳答案
使用语法 def receiver.method
您可以在特定对象 上定义方法。
class Dog
def bark
puts 'woof'
end
end
normal_dog = Dog.new
angry_dog = Dog.new
def angry_dog.bite
puts "yum"
end
normal_dog.class # => Dog
angry_dog.class # => Dog
angry_dog.bite # >> yum
normal_dog.bite # ~> -:15:in `<main>': undefined method `bite' for #<Dog:0x007f9a93064cf0> (NoMethodError)
请注意,尽管狗属于同一类 Dog
,但其中一只狗具有另一只狗没有的独特方法。
类也是一样。在类定义内部,self
指向该类。这对于理解至关重要。
class Foo
self # => Foo
end
现在让我们看看这两个类:
class Foo
def self.hello
"hello from Foo"
end
end
class Bar
end
Foo.class # => Class
Bar.class # => Class
Foo.hello # => "hello from Foo"
Bar.hello # ~> -:15:in `<main>': undefined method `hello' for Bar:Class (NoMethodError)
即使 Foo
和 Bar
都是 Class
类的实例(对象),其中之一有另一种方法没有。同样的事情。
如果您在方法定义中省略了 self
,那么它就变成了实例方法,它将在类的实例 上可用,而不是在类里面。请参阅第一段中的 Dog#bark
定义。
对于关闭,这里有几个关于如何定义类实例方法的方法:
class Foo
def self.hello1
"hello1"
end
def Foo.hello2
"hello2"
end
end
def Foo.hello3
"hello3"
end
Foo.hello1 # => "hello1"
Foo.hello2 # => "hello2"
Foo.hello3 # => "hello3"
关于ruby - self. 是什么意思?意思是在类方法中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15539703/