Understanding a class instance variable and python class

Suppose I have 2 classes in different scenarios.

Scenario 1

class MyClass():
    temp = 5

Scenario 2

class MyClass():
    temp = 5

    def myfunc(self):
          print self.temp

Now that the variable tempwill be considered both a class variable and an instance variable. I am confused because in both scenarios I can access the value of a variable tempusing both.

  • Object.Temp (behaves like an instance variable)

  • ClassName.Temp (behaves like a class variable)

I believe that similar questions have been asked before, but it will be of great help if someone can explain this in the context of my question.

+5
source share
3 answers

. (, int, str,...) . :

class MyClass():
    temp = []  
    def myfunc(self, val):
          self.temp.append(val)
          print self.temp

instance1 = MyClass()
instance1.myfunc(1)    # [1]
instance2 = MyClass()
instance2.myfunc(2)    # [1, 2]

, temp, .

, :

MyClass.temp.append(3)
print instance1.temp   # [1, 2, 3]
instance1.temp = []
print instance1.temp   # []         uses the instances temp
print instance2.temp   # [1, 2, 3]
del instance1.temp
print instance1.temp   # [1, 2, 3]  uses the class' temp again
+6

, MyClass.temp . obj.temp , obj.temp, -, . , :

>>> class MyClass(object):
...     temp = 5
... 
>>> a = MyClass()
>>> b = MyClass()
>>> a.temp
5
>>> b.temp
5
>>> b.temp = 6
>>> a.temp
5
>>> MyClass.temp = 7
>>> a.temp
7
>>> b.temp
6
>>> a.__dict__
{}
>>> b.__dict__
{'temp': 6}
>>> MyClass.__dict__
{..., 'temp': 7}

: mata , ( append()) obj.temp "" .

+5

temp - . , , , ( ) .

+2

All Articles