A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class’s methods. Class variables are not used as frequently as instance variables are. For Example
class Employee: company = 'google'
In this code company is a class attribute and it will shared with all its object it should not be defined in any method it is always outside the methods. We can also access it by Employee.company
A variable that is defined inside a method and belongs only to the current instance of a class.
class Employee: company = 'google' john = Employee() print(john.comapny) #print google john.comapny = 'Microsoft' print(john.comapny) #print Microsoft
In this code when we create an object then all attributes inside the object of instance attribute changing to these variables are only for this object.
Defining a Method
Inside a class a method can be defined with the keyword def and every method inside a class should have first parameter with name self which is pointing to current object For example.
class Employee: class Employee: company = 'google' salary = 10000 def getSalary(self): return self.salary john = Employee() print(john.getSalary())
In this code we define a method called getSallary() and pass a parameter self But when we create an object and call this method we did not need to add self parameter when we calling the method.
Define Method with Parameter
If want to add more parameters to method than we will put them after the self parameter and use them inside the method for example:
class Employee: company = 'google' salary = 10000 def getTaxAmount(self, taxPercentage): return self.salary*(taxPercentage/100) john = Employee() print(john.getTaxAmount(10)) #will print 1000.0
In this code we define a method which will return us the actual amount of tax and we will provide the tax percentage as parameter, so when we define method we use 2 parms and when we call the method we use only one input parm only not the self