random
module
import random
randint()
randint(0,5)
will generate random numbers between 1 & 5random()
random.random() * 100
choice()
random.choice( ['red', 'black', 'green'] )
shuffle()
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
randrange()
random.randrange(start, stop[, step])
Dependency injection is a software design pattern that allows a programmer to specify the dependencies for a class in a separate location from the class itself. The main idea behind dependency injection is to reduce the tight coupling between software components by allowing the dependencies of a class to be injected at runtime, rather than being hard-coded into the class.
There are several benefits to using dependency injection:
It allows a programmer to specify the dependencies of a class in a separate location, which can make the class easier to test and maintain.
It makes it easier to change the dependencies of a class without modifying the class itself.
It can help to decouple the dependencies of a class from the class itself, which can make it easier to reuse the class in different contexts.
There are several different ways to implement dependency injection, including:
The specific technique used may depend on the programming language and the specific needs of the application.
Constructor injection is a common way to implement dependency injection, because it allows the dependencies of a class to be specified when the class is instantiated. This can be especially useful when the dependencies are required for the class to function properly.
Say we have a class called Person
that has a dependency on a Car
class. We can use dependency injection to specify the Car
dependency in a separate location from the Person class itself. In this case, the dependency is injected through the constructor of the class (Person
).
Car
classclass Car:
def __init__(self, make, model):
self.make = make
self.model = model
def drive(self):
print(f"Driving a {self.make} {self.model}")
Person
class with a drive
method that has a Car
dependencyclass Person:
def __init__(self, car):
self.car = car
def drive(self):
self.car.drive()
Car
and pass it to the Person
constructor as a dependencycar = Car("Toyota", "Camry")
person = Person(car)
person.drive()
# Outputs: 'Driving a Toyota Camry'
By using dependency injection, we were able to specify the Car
dependency in a separate location from the Person
class, which makes it easier to test and maintain the Person
class.