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

book
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.

python
class Class:
attribute = "Value"

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

python
Class.attribute

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

class User:
username = "top_user_name"
age = 20

bob = User()

print(User.age)
print(bob.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:

class User:
pass

bob = User()
bob.name = "Bob"

print(bob.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.

class User:
name = "User"
john = User()
bob = User()
bob.name = "Bob"

print("john.name =", john.name)
print("bob.name =", bob.name)
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?

question mark

What is attribute?

Select the correct answer

question mark

What can the attributes be?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 1. Chapitre 3
some-alt