Ruby 和 Python 中的作用域 [英] Scope in Ruby and Python

查看:49
本文介绍了Ruby 和 Python 中的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在同时学习 Ruby 和 Python,我注意到的一件事是这两种语言似乎对作用域的处理方式不同.这是我的意思的一个例子:

I've been learning Ruby and Python concurrently and one of the things I noticed is that these 2 languages seem to treat scope differently. Here's an example of what I mean:

# Python
a = 5
def myfunc():
  print a

myfunc() # => Successfully prints 5

# Ruby
a = 5
def myfunc
  puts a
end

myfunc # => Throws a "NameError: undefined local variable or method `a' for main:Object"

似乎 def 块可以访问在 Python 中但不是在 Ruby 中的直接作用域之外声明的变量.有人可以确认我的理解是否正确吗?如果是这样,这些范围思考方式中的一种是否在编程中更常见?

It appears that def block can access variables declared outside of its immediate scope in Python but not in Ruby. Can someone confirm whether my understanding is correct? And if so, whether one of these ways of thinking of scope is more common in programming?

推荐答案

免责声明:我不是 Python 专家

Disclaimer: I'm no python expert

在 python 中,在模块中定义的变量默认是模块变量,因此是该模块的全局变量.在 Ruby 中,当您定义小写变量时,它始终是一个局部变量.局部变量只能在定义它们的块中以及在该块中定义的包装变量的 procs/lambdas 中访问.

In python, where variables defined in a module are, by default, module variables and as such global to that module. In Ruby, when you define a lowercase variable, it is always a local variable. Local variables are only accessible in the block that defined them and in procs/lambdas defined in that block that wrap the variable.

在 Ruby 中,对于跨作用域的变量,它需要是:

In Ruby, for a variable to cross scopes, it needs to be either:

  • 常量 (ALL_CAPS):如果前缀正确,则始终可访问
  • 类变量(@@double_at):始终可以从定义类和任何子类访问,但不能从外部访问
  • 实例变量 (@single_at):只能从该对象内部访问,并从外部使用 getter 方法/get_instance_variable.
  • 全局 ($starts_with_dollar):一个坏主意.跨越所有范围,无需范围界定.不要使用!
  • A constant (ALL_CAPS): Always accessible, if prefixed with the right scope
  • Class variable (@@double_at): Always accessible from the defining class and any subclasses, but not from outside
  • Instance variable (@single_at): Accessible only from within that object, and from outside with getter methods/get_instance_variable.
  • Global ($starts_with_dollar): A bad idea. Crosses all scopes, no scoping needed. Do not use!

这篇关于Ruby 和 Python 中的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆