Daily Reading 4
Fixtures Classes Recursion
What are the key differences between classes and objects in Python, and how are they used to create and manage instances of a class?
A class a sort of blueprint that can be used to make objects. A class defines variables and functions to be contained within the future objects, and upon creating an object via an assignment operator referencing the class. After the object is defined, its base properties and functions inherited from the class definitions, but can be updated later. If you made objectA and objectB using the default values you have previously made for classY, and then later modify the values of objectB, objectA will not be modified in any way, as the objects, despite coming from the same source, are different iterations, or “instances” of that class.
Explain the concept of recursion and provide an example of how it can be used to solve a problem in Python. What are some best practices to follow when implementing a recursive function?
A recursive function, to work properly and follow common best practice, must have both a base case, and a recursive case. A base case is a value that the recursive function can be called by that will return another value without the need to process it in any capacity, which serves to break the recursion loop, while the recursion case is any values provided that are outside the base case. For values outside the base case, a recursive function will loop in on itself, calling itself with a new value, and (hopefully) getting closer to reaching an input value that matches the base case. If a function doesn’t call itself and make progress toward a base case where no further recursive processing is performed, then it is not a recursive function.
What is the purpose of pytest fixtures and code coverage in testing Python code? Explain how they can be used together to improve the quality and maintainability of a project.
Pytest fixtures are objects that contain values that you are going to want to use for the sake of testing multiple times, that can be treated as if they were a file. This can help to keep things cleaner than creating a global variable that exists only for the sake of being used for tests. Code coverage refers to, in general, how many cases your tests are actually accounting for. Having higher code coverage means you have provably tested that your code works as expected under many different starting conditions, which gives more confidence that every part of a complicated code base is working correctly.
To provide an extreme example of poor code coverage, take a small program that is supposed to add 2 numbers together. There is one test written for it, that checks if provided with 1 and 3, the program returns 4. The test passes. But with only that one test, you cannot tell that the program doesn’t do any adding at all, and is simply returning the number 4 every time.