instance variables python code example

Example 1: instance variable in python

class Car:    wheels = 4    # <- Class variable    def __init__(self, name):        self.name = name    # <- Instance variable

Example 2: instance variable python

class Car:    
  wheels = 4    # <- Class variable    
  
  def __init__(self, name):        
  	self.name = name    # <- Instance variable

Example 3: what is a ython instance

An object belonging to a class. e.g. if you had an Employee class, each 
individual employee would be an instance of the Employee class

Example 4: instance method in python

# Instance Method Example in Python 
class Student:
    
    def __init__(self, a, b):
        self.a = a
        self.b = b 
    
    def avg(self):
        return (self.a + self.b) / 2

s1 = Student(10, 20)
print( s1.avg() )

Example 5: class variable in python

# Class variables refer to variables that are made within a class.
# It is generated when you define the class.
# It's shared with all the instance of that class.
# Example:

class some_variable_holder(object):
    
    var = "This variable is created inside the class some_variable_holder()."
    
    def somefunc(self):
        print("Random function ran.")

thing = some_variable_holder()
another_thing = some_variable_holder()

# Both does the same thing because the same variable has been passed on from the class.
thing.var
another_thing.var

Example 6: how to assign a variable to a class in python

class Shark:
    animal_type = "fish"
    location = "ocean"
    followers = 5

new_shark = Shark()
print(new_shark.animal_type)
print(new_shark.location)
print(new_shark.followers)