web-dev-qa-db-ja.com

Python-なぜクラスで「self」を使用するのですか?

これらの2つのクラスはどのように異なりますか?

class A():
    x=3

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

大きな違いはありますか?

80
ryeguy

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

出力

Aのx:[1、1]
Bのx:[1]

135
Douglas Leeder

補足として:selfは実際にはランダムに選択されたWordで、誰もが使用しますが、thisfoo、またはmyselfを使用することもできますまたはその他の必要なものは、クラスのすべての非静的メソッドの最初のパラメーターにすぎません。これは、Word selfは言語構成ではなく、単なる名前であることを意味します。

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

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
22
TerrorBite

この例で説明していました

# 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 __== '__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

次に、出力は

 machine1.id 1 
 machine2.id 2 
 machine3.id 3 
 
 machine1.counter 3 
 machine2.counter 3 
 machine3.counter 3 
16
TMOTTM

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_は、「objから_color="red"_を取得しています」という意味です。

2番目の方法では、色を取得するオブジェクトを指定するselfがないため、グローバルな_color = 'blue'_を取得します。

3番目の方法では、selfの代わりに_obj2_-colorを取得する別のオブジェクトの名前を使用しました。 _color = 'green'_を取得します。

3
yabee-dabee