FANDOM


The object-oriented programming aspect of Python allows us to create variables at a Class Level and a Instance Level.

Variables at class level are considered class variables and variables at instance level are called instance variables.

Class Variables Edit

When we want to declare a variable that we aren't going to be changing between instances, that variable should be defined as a class variable.

class Person:
    species = "Human"

As shown above, class variables are defined within the class construction. They are owned by the class itself and these variables can be shared by all instances of said class. They will usually have the same value unless you are using the class variable to initialize a variable.

So if we create an instance of the "Person" class, we can then get the species variable the following way:

newPerson = Person()
print(newPerson.species)

it will return : Human


Instance VariablesEdit

When we want to declare a variable that will change across instances of a class, we should define them as instance variables.

Instance variables are owned by instances of the class. Meaning that for each object/instance of a class, the instance variables are different.

Instance variables are defined within methods, like the following:

class Person: 
    def __init__(self, name, age):
        # instance variables.
        self.name = name
        self.age = age

See that these variables are passed in by arguments/parameters when the instance is being initialized.

We can get these values similarly to how we get the class variables:

newPerson = Person("Renee", 27)
print(newPerson.name)
print(newPerson.age)



ReferencesEdit

Community content is available under CC-BY-SA unless otherwise noted.