Home  >  Article  >  Backend Development  >  The difference between python class variables and instance variables

The difference between python class variables and instance variables

(*-*)浩
(*-*)浩Original
2019-07-05 10:55:285778browse

In the Python Tutorial, class variables and instance variables are described like this:

The difference between python class variables and instance variables

 Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:

Generally speaking, instance variables are for each Data that is unique to each instance, while class variables are properties and methods shared by all instances of the class. (Recommended learning: Python video tutorial)

The difference between them is that instance variables are private to the object they belong to, while class variables are common to all objects

Class variables are also called global variables, which are characteristics of classes. The instance first looks for the instantiation variable, and then looks for the class variable. However, the instance variable only belongs to the instantiation variable, but the class variable can also be used to find the instance. Call. If the class variable has multiple inheritance relationships, you need to search according to the specified route. Let’s look at the code to understand it first

class A:
    aa=10
    def __init__(self,a,b):
        self.a=a
        self.b=b
a=A(5,20)

print(a.a)  #实例变量
print((a.aa))#实例读取类变量

#打印结果 
5
10

For more Python related technical articles, please visitPython Tutorial Column for learning!

The above is the detailed content of The difference between python class variables and instance variables. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn