Python中的全局变量、成员变量和实例变量

Global variables, member variables and instance variables in Python

能举个高亮显示全局变量、成员变量、实例变量的程序例子吗?我不确定我是否会在上下文中认出它们。最好是 Python,但也可以是其他类似的编程语言。

你问了 很多问题 一个!我会尽力回答每一个问题:)

变量 - 全局与局部

全局变量是那些范围是全局的变量,即在整个程序中可用。

相比之下,局部变量是那些驻留在一个特定范围、函数、循环内、特定条件内等的变量。

示例如下:

glb_var_1 = "some value"
glb_var_2 = "some other value"

def f1():
   local_var_1 = "this is local inside f1"

   print("f1(): We can use here all variables defined locally, i.e. inside f1():", local_var_1)
   print("f1(): We can use global var anywhere in program:", glb_var_1)

def f2():
   local_var_1 = "this is local inside f2"
   glb_var_1   = "this is local variable which is hiding global var of same name"

   print("f2(): locally inside f2():", local_var_1)
   print("f2(): same name as global var, but local to f2():", glb_var_1)

def f3():
    print("f3(): global var value would be one defined globally, not the one as defined in f2():", glb_var_1)

事实上,在 Python 中有一些函数可以为您提供所有定义的全局变量和局部变量的列表。 这些函数是:

globals()locals()分别

成员变量

成员变量就是在class中定义的那些变量。 这些变量可以在 class 的方法中的任何地方使用,也可以在 class 的对象名称中使用。

下面的例子可以清楚地说明这一点:

class SomeClass(object):

    def __init__(self):
        self.member_var_1 = "some value"
        self.member_var_2 = "some other value"

    def method1(self):
        print("Could use any member variables here:", self.member_var_1)
        self.member_var_1 = "new value"

    def method2(self):
        print("If this method is called after method1, we will get new value:", self.member_var_1)

# create object/instance of SomeClass
obj = SomeClass()

# could also use member variables like below
obj.member_var_1 = "new value modified outside method"

# similar to how we call the method of a class
obj.method2()

class 变量 vs 实例变量

我们在上面的代码清单中看到的成员变量,只不过是实例变量。 class 变量 是那些在class 级别可用的变量。这意味着,它对于 class 的所有实例都是相同的。 我们也可以使用 class 变量而不考虑任何 class 实例。

下面的例子会更好地解释它:

class SomeClass(object):

    class_var_1 = "some value"
    class_var_2 = "some other value"

    def some_method(self):
        print("Could use all class members, but need to use special syntax:", SomeClass.class_var_1)

print("Outside class method, no instance created, still can use class member:",  SomeClass.class_var_1)
obj = SomeClass()
obj.some_method()

我希望你现在明白了:)