- Python Class Attributes
- Introduction to class attributes
- How Python class attributes work
- When to use Python class attributes
- 1) Storing class constants
- 2) Tracking data across of all instances
- 3) Defining default values
- Summary
- Python Classes and Objects
- Create a Class
- The __init__() Method
- The self Parameter
- Attributes
- Instance Attribute
- Class Attribute
- Create an Object
- Access and Modify Attributes
- Methods
- Instance Methods
- Delete Attributes and Objects
Python Class Attributes
Summary: in this tutorial, you’ll learn about the Python class attributes and when to use them appropriately.
Introduction to class attributes
Let’s start with a simple Circle class:
class Circle: def __init__(self, radius): self.pi = 3.14159 self.radius = radius def area(self): return self.pi * self.radius**2 def circumference(self): return 2*self.pi * self.radius
Code language: Python (python)
The Circle class has two attributes pi and radius . It also has two methods that calculate the area and circumference of a circle.
Both pi and radius are called instance attributes. In other words, they belong to a specific instance of the Circle class. If you change the attributes of an instance, it won’t affect other instances.
Besides instance attributes, Python also supports class attributes. The class attributes don’t associate with any specific instance of the class. But they’re shared by all instances of the class.
If you’ve been programming in Java or C#, you’ll see that class attributes are similar to the static members, but not the same.
To define a class attribute, you place it outside of the __init__() method. For example, the following defines pi as a class attribute:
class Circle: pi = 3.14159 def __init__(self, radius): self.radius = radius def area(self): return self.pi * self.radius**2 def circumference(self): return 2 * self.pi * self.radius
Code language: Python (python)
After that, you can access the class attribute via instances of the class or via the class name:
object_name.class_attribute class_name.class_attribute
Code language: Oracle Rules Language (ruleslanguage)
In the area() and circumference() methods, we access the pi class attribute via the self variable.
Outside the Circle class, you can access the pi class attribute via an instance of the Circle class or directly via the Circle class. For example:
c = Circle(10) print(c.pi) print(Circle.pi)
Code language: Python (python)
3.14159 3.14159
Code language: Python (python)
How Python class attributes work
When you access an attribute via an instance of the class, Python searches for the attribute in the instance attribute list. If the instance attribute list doesn’t have that attribute, Python continues looking up the attribute in the class attribute list. Python returns the value of the attribute as long as it finds the attribute in the instance attribute list or class attribute list.
However, if you access an attribute, Python directly searches for the attribute in the class attribute list.
The following example defines a Test class to demonstrate how Python handles instance and class attributes.
class Test: x = 10 def __init__(self): self.x = 20 test = Test() print(test.x) # 20 print(Test.x) # 10
Code language: Python (python)
The Test class has two attributes with the same name ( x ) one is the instance attribute and the other is a class attribute.
When we access the x attribute via the instance of the Test class, it returns 20 which is the variable of the instance attribute.
However, when we access the x attribute via the Test class, it returns 10 which is the value of the x class attribute.
When to use Python class attributes
Class attributes are useful in some cases such as storing class constants, tracking data across all instances, and defining default values.
1) Storing class constants
Since a constant doesn’t change from instance to instance of a class, it’s handy to store it as a class attribute.
For example, the Circle class has the pi constant that is the same for all instances of the class. Therefore, it’s a good candidate for the class attributes.
2) Tracking data across of all instances
The following adds the circle_list class attribute to the Circle class. When you create a new instance of the Circle class, the constructor adds the instance to the list:
class Circle: circle_list = [] pi = 3.14159 def __init__(self, radius): self.radius = radius # add the instance to the circle list self.circle_list.append(self) def area(self): return self.pi * self.radius**2 def circumference(self): return 2 * self.pi * self.radius c1 = Circle(10) c2 = Circle(20) print(len(Circle.circle_list)) # 2
Code language: Python (python)
3) Defining default values
Sometimes, you want to set a default value for all instances of a class. In this case, you can use a class attribute.
The following example defines a Product class. All the instances of the Product class will have a default discount specified by the default_discount class attribute:
class Product: default_discount = 0 def __init__(self, price): self.price = price self.discount = Product.default_discount def set_discount(self, discount): self.discount = discount def net_price(self): return self.price * (1 - self.discount) p1 = Product(100) print(p1.net_price()) # 100 p2 = Product(200) p2.set_discount(0.05) print(p2.net_price()) # 190
Code language: Python (python)
Summary
- A class attribute is shared by all instances of the class. To define a class attribute, you place it outside of the __init__() method.
- Use class_name.class_attribute or object_name.class_attribute to access the value of the class_attribute .
- Use class attributes for storing class contants, track data across all instances, and setting default values for all instances of the class.
Python Classes and Objects
Classes and objects are the two main aspects of object-oriented programming.
A class is the blueprint from which individual objects are created. In the real world, for example, there may be thousands of cars in existence, all of the same make and model.
Each car was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your car is an instance (object) of the class Car.
In Python, everything is an object – integers, strings, lists, functions, even classes themselves.
However, Python hides the object machinery with the help of special syntax.
For example, when you type num = 42 , Python actually creates a new object of type integer with the value 42, and assign its reference to the name num .
Create a Class
To create your own custom object in Python, you first need to define a class, using the keyword class .
Suppose you want to create objects to represent information about cars. Each object will represent a single car. You’ll first need to define a class called Car.
Here’s the simplest possible class (an empty one):
Here the pass statement is used to indicate that this class is empty.
The __init__() Method
__init__() is the special method that initializes an individual object. This method runs automatically each time an object of a class is created.
The __init__() method is generally used to perform operations that are necessary before the object is created.
class Car: # initializer def __init__(self): pass
When you define __init__() in a class definition, its first parameter should be self .
The self Parameter
The self parameter refers to the individual object itself. It is used to fetch or set attributes of the particular instance.
This parameter doesn’t have to be called self , you can call it whatever you want, but it is standard practice, and you should probably stick with it.
self should always be the first parameter of any method in the class, even if the method does not use it.
Attributes
Every class you write in Python has two basic features: attributes and methods.
Attributes are the individual things that differentiate one object from another. They determine the appearance, state, or other qualities of that object.
In our case, the ‘Car’ class might have the following attributes:
Attributes are defined in classes by variables, and each object can have its own values for those variables.
There are two types of attributes: Instance attributes and Class attributes.
Instance Attribute
The instance attribute is a variable that is unique to each object (instance). Every object of that class has its own copy of that variable. Any changes made to the variable don’t reflect in other objects of that class.
In the case of our Car() class, each car has a specific color and style.
# A class with two instance attributes class Car: # initializer with instance attributes def __init__(self, color, style): self.color = color self.style = style
Class Attribute
The class attribute is a variable that is same for all objects. And there’s only one copy of that variable that is shared with all objects. Any changes made to that variable will reflect in all other objects.
In the case of our Car() class, each car has 4 wheels.
# A class with one class attribute class Car: # class attribute wheels = 4 # initializer with instance attributes def __init__(self, color, style): self.color = color self.style = style
So while each car has a unique style and color, every car will have 4 wheels.
Create an Object
You create an object of a class by calling the class name and passing arguments as if it were a function.
# Create an object from the 'Car' class by passing style and color class Car: # class attribute wheels = 4 # initializer with instance attributes def __init__(self, color, style): self.color = color self.style = style c = Car('Sedan', 'Black')
Here, we created a new object from the Car class by passing strings for the style and color parameters. But, we didn’t pass in the self argument.
This is because, when you create a new object, Python automatically determines what self is (our newly-created object in this case) and passes it to the __init__ method.
Access and Modify Attributes
The attributes of an instance are accessed and assigned to by using dot . notation.
# Access and modify attributes of an object class Car: # class attribute wheels = 4 # initializer with instance attributes def __init__(self, color, style): self.color = color self.style = style c = Car('Black', 'Sedan') # Access attributes print(c.style) # Prints Sedan print(c.color) # Prints Black # Modify attribute c.style = 'SUV' print(c.style) # Prints SUV
Methods
Methods determine what type of functionality a class has, how it handles its data, and its overall behavior. Without methods, a class would simply be a structure.
In our case, the ‘Car’ class might have the following methods:
Just as there are instance and class attributes, there are also instance and class methods.
Instance methods operate on an instance of a class; whereas class methods operate on the class itself.
Instance Methods
Instance methods are nothing but functions defined inside a class that operates on instances of that class.
Now let’s add some methods to the class.
- showDescription() method: to print the current values of all the instance attributes
- changeColor() method: to change the value of ‘color’ attribute
class Car: # class attribute wheels = 4 # initializer / instance attributes def __init__(self, color, style): self.color = color self.style = style # method 1 def showDescription(self): print("This car is a", self.color, self.style) # method 2 def changeColor(self, color): self.color = color c = Car('Black', 'Sedan') # call method 1 c.showDescription() # Prints This car is a Black Sedan # call method 2 and set color c.changeColor('White') c.showDescription() # Prints This car is a White Sedan
Delete Attributes and Objects
To delete any object attribute, use the del keyword.
You can delete the object completely with del keyword.