concept data attribute in category python

appears as: data attribute, data attributes, data attributes
Get Programming: Learn to code with Python

This is an excerpt from Manning's book Get Programming: Learn to code with Python.

After you start defining the class, you’ll have to decide how your object will be initialized. For the most part, this involves deciding how you’ll represent your object and the data that will define it. You’ll initialize these objects. The object properties are called data attributes of the object.

A data attribute of one object is another object. Your object may be defined by more than one data attribute. To tell Python that you want to define a data attribute of the object, you use a variable named self with a dot after it. In the Circle class, you initialize a radius as the data attribute of a circle, and initialize it to 0:

class Circle(object):
    def __init__(self):
        self.radius = 0

Notice that in the definition of __init__, you take one parameter named self. Then, inside the method, you use self. to set a data attribute of your circle. The variable self is used to tell Python that you’ll be using this variable to refer to any object you’ll create of the type Circle. Any circle you create will have its own radius accessible through self.radius. At this point, notice that you’re still defining the class and haven’t created any specific object yet. You can think of self as a placeholder variable for any object of type Circle.

Inside __init__, you use self.radius to tell Python that the variable radius belongs to an object of type Circle. Every object you create of type Circle will have its own variable named radius, whose value can differ between objects. Every variable defined using self. refers to a data attribute of the object.

  • A class defines data attributes (properties) and methods (operations).
  • Figure 38.2. The game after creating two player objects. The position and size of each square varies each time the program is run.
    sitemap

    Unable to load book!

    The book could not be loaded.

    (try again in a couple of minutes)

    manning.com homepage
    test yourself with a liveTest