Object Oriented Programming

Class and Instance Variables in Python

Used declare variables within a class. There are two main types: class variables, which have the same value across all class instances (i.e. static variables), and instance variables, which have different values for each object instance.


Syntax
class ClassName(object):
  class_variable = value #value shared across all class instances

  def __init__(instance_variable_value):
    self.instance_variable = instance_variable_value #value specific to instance. Instance variables are usually initialized in methods

#accessing instance variable
class_instance = ClassName()
class_instance.instance_variable

#accessing class variable
ClassName.class_variable
class_instance.class_variable

Notes

In Python, using leading and trailing double underscores is the naming convention for indicating a variable is meant to be private.


Example
class Car(object):
  wheels = 4

    def __init__(self, make):
      self.make = make

newCar = Car("Honda")
print ("My new car is a {}".format(newCar.make))
print ("My car, like all cars, has {%d} wheels".format(Car.wheels))

See Also
Documentation

Classes - Python Documentation

Add to Slack

< Class Declaration & Structure   |   Constructor >

© 2018 SyntaxDB. All Rights Reserved.