Python - 为什么在课堂上使用"self"?

rye*_*guy 80 python oop

这两个班级有何不同?

class A():
    x=3

class B():
    def __init__(self):
        self.x=3
Run Code Online (Sandbox Code Playgroud)

有什么显着差异吗?

Dou*_*der 135

A.x是一个类变量. Bself.x是一个实例变量.

Ax被实例之间共享.

可以更容易地证明可以像列表一样修改的东西的区别:

#!/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)
Run Code Online (Sandbox Code Playgroud)

产量

A的x:[1,1]
B的x:[1]

  • 也许还会发布你的脚本的输出,然后你可以看到差异,而无需复制和自己运行它... (8认同)
  • 我添加了输出. (7认同)
  • 那么python的自身是否与Java相当?请原谅noobishness (2认同)
  • @Jean - Yes-ish - self必须只是实例方法的第一个参数的常规名称 - 而python显式地将实例方法的当前实例作为实例方法的第一个参数传递.但它与Java的工作完全相同 (2认同)

And*_*dré 54

正如一个侧面说明:self实际上只是一个随机选择的话,每个人都使用,但你也可以使用this,foomyself或者任何你想要的东西,它只是一类每一个非静态方法的第一个参数.这意味着该单词self不是语言结构,而只是一个名称:

>>> class A:
...     def __init__(s):
...        s.bla = 2
... 
>>> 
>>> a = A()
>>> a.bla
2
Run Code Online (Sandbox Code Playgroud)

  • 为什么这是一个答案而不是评论 (2认同)

Ter*_*ite 22

Ax是一个类变量,除了在实例中特别重写之外,它将在A的所有实例之间共享.Bx是一个实例变量,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
Run Code Online (Sandbox Code Playgroud)


TMO*_*TTM 16

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

# 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
Run Code Online (Sandbox Code Playgroud)

然后输出将通过

machine1.id 1
machine2.id 2
machine3.id 3

machine1.counter 3
machine2.counter 3
machine3.counter 3