What is the difference in the use of a variable declared inside the class and inside the __init__ method?


#1

https://www.codecademy.com/courses/learn-python/lessons/introduction-to-classes/exercises/its-not-all-animals-and-fruits?action=resume_content_item

I can influence (change) these variables both inside the class methods and also outside the class when working with an object instance


#2

Class variables are available to every member (instance) of a class. They can assign attributes that will be applicable to every member. They can also contain information about the class itself, i.e., its size or list of members. This information can be made available to the individual instances.

Instance variables are, of course, unique to the particular instance.

class Lion:
    species = "Panthera leo"   # class variables
    number = 0
    names = []
    def __init__(self, name, sex):
        self.name = name
        self.sex = sex
        Lion.names.append(self.name)  # change a class variable when a new member is instantiated
        Lion.number += 1
        
leo = Lion("Leo", "M")

dorothy = Lion("Dorothy", "F")

print(leo.sex)
print(dorothy.sex)
print(leo.species)
print(Lion.number)  # available to the class
print(Lion.names)   
print(leo.number)   # available to the members
print(leo.names)

Output:

M
F
Panthera leo
2
['Leo', 'Dorothy']
2
['Leo', 'Dorothy']