Attributes
- Python course
- Intermediate
- Lesson 2/116
- 5 min
Learn class and instance attributes.
Class attribute
A class attribute is a variable defined directly in the class body. All instances share this value.
Example: class Product:\n tax_rate = 0.18. Here tax_rate is a class attribute. It is accessed as Product.tax_rate or through an instance as p.tax_rate. The default value of a class attribute must be a constant.
Instance attribute
An instance attribute is data specific to each instance. It is assigned through self, usually inside the __init__ method. For now we can also assign it from outside.
Example: p = Product(); p.name = "Pen". Here p.name belongs only to p; another instance does not share the name value. An instance attribute is separate from a class attribute.
Practice Add an attribute to the Product class
Define a class named Product. Add the class attribute tax_rate = 0.18 in the body. After the class, write print(Product.tax_rate).
Starter code
# Define the Product classSample solution
# Define the Product class
class Product:
tax_rate = 0.18
print(Product.tax_rate)Expected output
0.18
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the class attribute
class Product:
____ = 0.18
class Product:
tax_rate = 0.18
Explanation: tax_rate is a class attribute; it is written directly in the body.
2 Which one is an instance attribute?
- class Product: tax_rate = 0.18
- p = Product(); p.name = "Pen" Correct answer
- Product.tax_rate = 0.20
- class Product: pass
Explanation: The p.name assignment creates an instance attribute; it belongs only to p.
3 Match the attribute types
| Term | Meaning |
|---|---|
tax_rate = 0.18 |
Class attribute |
self.name |
Instance attribute |
Product.tax_rate |
Access via class |