在Python类中使用“self”定义成员有什么区别?

问题描述 投票:0回答:5

这两个类别有何不同?

class A():
    x=3

class B():
    def __init__(self):
        self.x=3

有什么显着差异吗?

python oop
5个回答
147
投票

A.x
是一个类变量
B
self.x
是一个 实例变量

A
x
在实例之间共享。

用可以修改的东西(如列表)来展示差异会更容易:

#!/usr/bin/env python

class A:
    x = []
    def add(self):
        self.x.append(1)

class B:
    def __init__(self):
        self.x = []
    def add(self):
        self.x.append(1)

x = A()
y = A()
x.add()
y.add()
print("A's x:", x.x)

x = B()
y = B()
x.add()
y.add()
print("B's x:", x.x)

输出

A's x: [1, 1]
B's x: [1]

61
投票

作为旁注:

self
实际上只是一个随机选择的单词,每个人都使用,但您也可以使用
this
foo
,或
myself
或任何其他您想要的,它只是第一个参数类的每个非静态方法。这意味着单词
self
不是一个语言结构,而只是一个名称:

>>> class A:
...     def __init__(s):
...        s.bla = 2
... 
>>> 
>>> a = A()
>>> a.bla
2

25
投票

A.x 是一个类变量,将在 A 的所有实例之间共享,除非在实例中专门重写。 B.x 是一个实例变量,B 的每个实例都有自己的版本。

我希望下面的Python示例能够澄清:


    >>> class Foo():
    ...     i = 3
    ...     def bar(self):
    ...             print 'Foo.i is', Foo.i
    ...             print 'self.i is', self.i
    ... 
    >>> f = Foo() # Create an instance of the Foo class
    >>> f.bar()
    Foo.i is 3
    self.i is 3
    >>> Foo.i = 5 # Change the global value of Foo.i over all instances
    >>> f.bar()
    Foo.i is 5
    self.i is 5
    >>> f.i = 3 # Override this instance's definition of i
    >>> f.bar()
    Foo.i is 5
    self.i is 3

18
投票

我曾经用这个例子来解释过

# By TMOTTM

class Machine:

    # Class Variable counts how many machines have been created.
    # The value is the same for all objects of this class.
    counter = 0

    def __init__(self):

        # Notice: no 'self'.
        Machine.counter += 1

        # Instance variable.
        # Different for every object of the class.
        self.id = Machine.counter

if __name__ == '__main__':
    machine1 = Machine()
    machine2 = Machine()
    machine3 = Machine()

    #The value is different for all objects.
    print 'machine1.id', machine1.id
    print 'machine2.id', machine2.id
    print 'machine3.id', machine3.id

    #The value is the same for all objects.
    print 'machine1.counter', machine1.counter
    print 'machine2.counter', machine2.counter
    print 'machine3.counter', machine3.counter

然后输出将是

机器1.id 1
机器2.id 2
machine3.id 3

机器1.计数器3
机器2.计数器3
machine3.计数器3

4
投票

我刚刚开始学习Python,这也让我困惑了一段时间。为了弄清楚这一切是如何工作的,我想出了这段非常简单的代码:

# Create a class with a variable inside and an instance of that class
class One:
    color = 'green'

obj2 = One()


# Here we create a global variable(outside a class suite).
color = 'blue'         

# Create a second class and a local variable inside this class.       
class Two:             
    color = "red"

    # Define 3 methods. The only difference between them is the "color" part.
    def out(self):     
        print(self.color + '!')

    def out2(self):
        print(color + '!')

    def out3(self):
        print(obj2.color + '!')

# Create an object of the class One
obj = Two()

当我们致电

out()
时,我们得到:

>>> obj.out()

red!

当我们打电话给

out2()
时:

>>> obj.out2()

blue!

当我们打电话给

out3()
时:

>>> obj.out3()

green!

因此,在第一个方法中

self
指定Python应该使用“属于”我们创建的类对象的变量(属性),而不是全局变量(在类之外)。所以它使用
color = "red"
。在该方法中,Python 隐式地用
self
替换我们创建的对象的名称 (
obj
)。
self.color
的意思是“我从
color="red"
得到
obj

在第二种方法中,没有

self
来指定应从中获取颜色的对象,因此它获取全局对象
color = 'blue'

在第三种方法中,我们使用

self
代替
obj2
- 要从中获取
color
的另一个对象的名称。它变得
color = 'green'

© www.soinside.com 2019 - 2024. All rights reserved.