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

In-Depth Python OOP

1. OOP Concepts
2. Inheritance
3. Encapsulation
4. Polymorphism and Abstraction
5. Magic Methods

bookAttributes

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:

12345678
class User: username = "top_user_name" age = 20 bob = User() print(User.age) print(bob.age)
copy

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:

1234567
class User: pass bob = User() bob.name = "Bob" print(bob.name)
copy

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.

123456789
class User: name = "User" john = User() bob = User() bob.name = "Bob" print("john.name =", john.name) print("bob.name =", bob.name)
copy

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 is attribute?

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

What can the attributes be?

What can the attributes be?

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

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

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 3
some-alt