QuesAns Print Page – CSKC
Sign In

Search

siteicon
Q&A CBSE12A-2018-B02B #6116

Question:

class Vehicle:                        #Line 1
    Type = 'Car'                      #Line 2
    def __init__(self, name):         #Line 3
        self.Name = name              #Line 4
    def Show(self):                   #Line 5
        print self.Name,Vehicle.Type  #Line 6

V1=Vehicle("BMW")                     #Line 7
V1.Show()                             #Line 8
Vehicle.Type="Bus"                    #Line 9
V2=Vehicle("VOLVO")                   #Line 10
V2.Show()                             #Line 11

(i) What is the difference between the variable in Line 2 and Line 4 in the above Python code?

(ii) Write the output of the above Python code.

Answer:

(i) The variable in Line 2 is a class attribute. This belongs to the class itself. These attributes will be shared by all the instances. The variable in Line 4 is an instance attribute. Each instance creates a
separate copy of these variables.

(ii) BMW Car
VOLVO Bus