M
M
Magic Code2020-05-20 15:33:53
Python
Magic Code, 2020-05-20 15:33:53

What is the difference between class and instance variables?

I want to catch the essence, the meaning in class instance variables?
I understand that a class variable is something like a global variable and all instances can use it, while a class variable is a local variable and only an instance of the class can use it? In what cases, then it is worth setting a class variable?

class Mag:
    lvl = 100

    def __init__(self, name, rank):
        self.name = name
        self.rank = rank

    def spell(self, enemy) -> None:
        if enemy == 'human':
            print('You can`t kill a human')
        else:
            print(f"{self.name} make a spell on {enemy}!")


Thanks in advance for the clarification!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
szafranji, 2020-05-20
@szafranji

I advise you to read the book by M. Lutz, it seems, the second volume.
There, just "by atoms", the author analyzes the principles of work of classes, instances and OOP as a whole.
If the pens got to OOP, then you need to know in sufficient detail how this paradigm works, everything is explained in the book.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question