Course Content
In-Depth Python OOP
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
:
class User: username = "top_user_name" age = 20 bob = User() print(User.age) print(bob.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 User: pass bob = User() bob.name = "Bob" print(bob.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.
class User: name = "User" john = User() bob = User() bob.name = "Bob" print("john.name =", john.name) print("bob.name =", bob.name)
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.
Thanks for your feedback!