Quotes

Friday, November 1, 2019

Python Misc

1) Class Variables - defined in side the class and outside of any methods()
Class variables in python are defined just after the class definition and outside of any methods:
class SomeClass:
    variable_1 = “ This is a class variable”
    variable_2 = 100   #this is also a class variable


2) Instance Variables- defined inside of the instance methods()
Unlike class variables, instance variables should be defined within methods:
class SomeClass:
    variable_1 = “ This is a class variable”
    variable_2 = 100    #this is also a class variable.

    def __init__(self, param1, param2):
        self.instance_var1 = param1
        #instance_var1 is a instance variable
 self.instance_var2 = param2   
        #instance_var2 is a instance variable
 
 
Let’s instantiate above class and do some introspections about those instances and above class:
>>> obj1 = SomeClass("some thing", 18)
#creating instance of SomeClass named obj1
>>> obj2 = SomeClass(28, 6)
#creating a instance of SomeClass named obj2

>>> obj1.variable_1
'a class variable'

>>> obj2.variable_1
'a class variable'



So as seen above, both obj1 and obj2 gives the same value when variable_1 is accessed, which is the normal behavior that we should expect from a class variable. Let’s find about instance variables:
>>> obj1.instance_var1
'some thing'
>>> obj2.instance_var1
28

 
1) Class methods(cls)-- cls never used. 2) Instance methogs(self, args). self used to access values

class SomeClass:    
    def create_arr(self): # An instance method
        self.arr = []
    
    def insert_to_arr(self, value):  #An instance method
        self.arr.append(value)
 
We can instantiate above class as obj3, and do some investigations as follows:
>>> obj3 = SomeClass()
>>> obj3.create_arr()
>>> obj3.insert_to_arr(5)
>>> obj3.arr
[5]


class SomeClass:
    def create_arr(self): # An instance method
        self.arr = []
    
    def insert_to_arr(self, value):  #An instance method
        self.arr.append(value)
        
    @classmethod
    def class_method(cls):
        print("the class method was called")

Without even instantiating an object, we can access class methods as follows:
SomeClass.class_method()

 
self:

class SomeClass:
    def __init__(self):
        self.arr = [] 
        #All SomeClass objects will have an array arr by default
    
    def insert_to_arr(self, value):
        self.arr.append(value)
So now let’s create two objects of SomeClass and append some values for their arrays:
obj1 = SomeClass()
obj2 = SomeClass()
obj1.insert_to_arr(6)


SomeClass.inseart_to_arr(obj1, 6)

No comments:

Post a Comment