1
 class Dog:
    breed='German'
    def __init__(self,name,age):
        self.name=name
        self.age=age
    
d1=Dog('fluffy',10)
d2=Dog('pookie',5)
d1.breed='Pitbull'
print(d1.breed)
print(d2.breed)

output-

Pitbull
German

I created a class variable breed and later on i tried to change the value of it by using the instance d1 and as we know that only single copy of class variable is available so effect should have been visible in all the copies but the same does not hold true here,why?

  • You can change the class variable by doing `Dog.breed = 'Pitbull'` – Tom McLean Sep 22 '22 at 11:23
  • I know I can do that but I found it written everywhere that if any changes made to the class variable by any instance , the same will hold true everywhere since a single copy exists of the class variable. – Shiva Gupta Sep 22 '22 at 11:25
  • 3
    Setting `d1.breed` does not actually modify `Dog.breed`, instead, it adds a `breed` attribute to the `d1` instance which will effectively hide the class attribute. – joanis Sep 22 '22 at 11:26
  • Is there a way to still access the breed attribute of class with d1 instance while keeping its newly created breed attribute? – Shiva Gupta Sep 22 '22 at 11:30
  • @ShivaGupta you can do `d1.__class__.breed`. https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables – Tom McLean Sep 22 '22 at 11:31

0 Answers0