Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Attributes | OOP Concepts
In-Depth Python OOP
course content

Зміст курсу

In-Depth Python OOP

Attributes

About Attributes

In object-oriented programming, attributes are variables that are associated with a class or instance. They can store data values or other objects.

You can access an attribute by using the class or instance name followed by a dot . and the attribute name.

Let's consider an example of creating attributes for the User class. The attributes will be username and age:

In the above example, we created attributes for our class. As you can see, we can access the class attribute User through its instance bob.

In Python, attributes can belong to a class or an instance. To assign an attribute to an instance, you can use an assignment statement with the attribute name:

Class and Instance Attributes

Class attributes are commonly used as constants or default values, while instance attributes are utilized as variables that are specific to each instance.

If an instance does not have a particular attribute, the interpreter searches for it in the class definition. This mechanism allows attributes to be shared among all instances of a class.

In the example above, we created two instances (john and bob) of the User class. We assigned a new value to the name attribute of the bob instance, making it its own instance attribute. The john instance does not have its own instance attribute, so it takes the value from its class User, which means it uses the class attribute.

1. What is attribute?
2. What can the attributes be?

What is attribute?

Виберіть правильну відповідь

What can the attributes be?

Виберіть кілька правильних відповідей

Все було зрозуміло?

Секція 1. Розділ 3
We're sorry to hear that something went wrong. What happened?
some-alt