Inclass-based,object-oriented programming, aclass variable is avariable defined in aclass of which a single copy exists, regardless of how manyinstances of the class exist.[1][2][3][4][5]
A class variable is not aninstance variable. It is a special type ofclass attribute (or class property,field, or data member). The same dichotomy betweeninstance andclass members applies tomethods ("member functions") as well; a class may have bothinstance methods andclass methods.
In some languages, class variables and class methods are either statically resolved, not viadynamic dispatch, or their memorystatically allocated at compile time (once for the entire class, asstatic variables), not dynamically allocated at run time (at every instantiation of an object). In other cases, however, either or both of these are dynamic. For example, if classes can be dynamically defined (at run time), class variables of these classes are allocated dynamically when the class is defined, and in some languages class methods are also dispatched dynamically.
Thus in some languages,static member variable orstatic member function are used synonymously with or in place of "class variable" or "class function", but these are not synonymous across languages. These terms are commonly used inJava,C#,[5] andC++, where class variables and class methods are declared with thestatic keyword, and referred to asstatic member variables orstatic member functions.
structRequest{staticintcount;intnumber;Requestobject(){number=count;// modifies the instance variable "this->number"++count;// modifies the class variable "Request::count"}};intRequest::count=0;
In this C++ example, the class variableRequest::count isincremented on each call to theconstructor, so thatRequest::count always holds the number of Requests that have been constructed, and each new Request object is given anumber in sequential order. Sincecount is a class variable, there is only one objectRequest::count; in contrast, each Request object contains its own distinctnumber field.
Also note that the variableRequest::count is initialized only once.
classDog:vertebrate_group="mammals"# class variabledog_1=Dogprint(dog_1.vertebrate_group)# accessing the class variable
In the above Python code, it does not provide much information as there is only class variable in the Dog class that provide the vertebrate group of dog as mammals. In instance variable, you could customize your own object (in this case, dog_1) by having one or moreinstance variables in the Dog class.
This can also be type hinted usingClassVar.
fromtypingimportClassVarclassDog:vertebrate_group:ClassVar[str]="mammals"