Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between class variable and class attribute

Would you please explain the difference between class variable and class attribute?

According to this web-page, class attributes are variables owned by the class itself.

For example:

class MP3FileInfo(FileInfo):
    "store ID3v1.0 MP3 tags"
    tagDataMap = {"title"   : (  3,  33, stripnulls),
                  "artist"  : ( 33,  63, stripnulls),
                  "album"   : ( 63,  93, stripnulls),
                  "year"    : ( 93,  97, stripnulls),
                  "comment" : ( 97, 126, stripnulls),
                  "genre"   : (127, 128, ord)}

The web page says tagDataMap is a class attribute. But according to Tutorialspoint.com, "class variable is a variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods."

So what Tutorialspoint.com calls class variable and what diveintopython.net calls class attribute are the same thing? I believe there are differences between these two terms and I would like to learn.

Thank you!

like image 822
Friendly User Avatar asked Nov 01 '22 02:11

Friendly User


1 Answers

I was a little confused by the question. Thus, I thought it made sense to walk back to a more general discussion on object oriented principles to help with the clarification (referencing some of my older teaching notes).

To create a class, you write a class definition. A class definition is a set of statements that define a class's method and data attributes.

Extending this, within the context of object oriented programming, an object, which is created from a class (which is the blueprint), has both data and procedures. The data in that object that is created from the class is known as the objects data attributes. In general, an object's data attributes are simply variables that reference data. The procedures that an object performs are the methods. Thus, the object, which is created from the class, is, conceptually, a self-contained unit that consists of data attributes and methods that operate on the data attributes.

An example (which hopefully makes things clear. Let us say that we have an insect class. The insect class describes the data attributes and methods that a particular type of object may have. From this class, we can create 2 objects: a hornet object and a mosquito object. The hornet object is an instance of the insect class. It has the data attributes and methods described by the insect class. Furthermore, the mosquito object is an instance of the insect class. It also has the data attributes and methods described by the insect class.

like image 55
Nathaniel Payne Avatar answered Nov 15 '22 04:11

Nathaniel Payne