Python is an Object-Oriented Programming (OOP) language. We can use classes in Python. A class can contain both data and methods. Using the methods of a class, we can access or operate on the data.
Let’s understand Python classes and objects with an example. Let’s say we want to generate the first 100 prime numbers and put them in a Python list. Later, we can print the list of prime numbers or we can check whether a given number is within the first 100 prime numbers.
Now, we can easily write this program using a Python class.
class PrimeNumbers: prime_numbers = list() def __init__(self, *numbers): for n in numbers: self.prime_numbers.append(n) def print_prime_numbers(self): print(self.prime_numbers) primes = PrimeNumbers(2, 3, 5) primes.print_prime_numbers()
PrimeNumbers is the name of the Python class. “def __init__(self, *numbers)” is the constructor. A Python constructor is a method that gets called every time an object is created. Here, we can create a Python object with an arbitrary number of prime numbers. So, the constructor is defined with arbitrary arguments (What are arbitrary arguments in Python?) that contain a number of prime numbers. In our program, we are creating the primes object with the first three prime numbers 2, 3, and 5. Please note that we can also define a constructor that takes no arguments. In that case, such constructor should be defined like this:






0 Comments