Python - why use “self” in a class?

后端 未结 5 1095
夕颜
夕颜 2020-11-28 19:56

How do these 2 classes differ?

class A():
    x=3

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

Is there any significant difference?

5条回答
  •  执念已碎
    2020-11-28 20:45

    A.x is a class variable, and will be shared across all instances of A, unless specifically overridden within an instance. B.x is an instance variable, and each instance of B has its own version of it.

    I hope the following Python example can clarify:

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

提交回复
热议问题