What this class covered
- Single and multiple inheritance, and the MRO, files 139 to 141
- Multilevel, hierarchical and hybrid inheritance, files 142 to 145
- Polymorphism, and overloading with default parameters, files 146 to 149
- Method overriding, files 150 and 151
- Abstraction with ABC and @abstractmethod, files 152 to 154
- Hiding the details: a car and a test case runner, files 155 and 156
- Static variables and static methods, files 157 and 158
- Tasks and announcements: exercises up to 158, your GitHub repository, tomorrow's class, Tester Town
- A child class names its parent in brackets,
class LoginTest(BaseTest):, and gets the parent's methods. There is noextendskeyword. - Python supports single, multiple, multilevel, hierarchical and hybrid inheritance. When two parents have a method with the same name, the parent listed first wins: that order is the MRO.
- A parent's double-underscore members do not reach a child by their plain name: Python renames them after the class they are written in.
- Python does not support method overloading in the traditional sense: a second
defwith the same name replaces the first. A default parameter is the way round it. - Overriding: a child class writes its own version of a parent's method, and the class of the object you build decides which one runs.
- An abstract class inherits
ABCand marks its incomplete methods with@abstractmethod. Python will not build it, nor a child that leaves any of those methods incomplete. - A variable written in the class body is shared by every object, with no static keyword. A
@staticmethodtakes noselfand is called on the class, with no object.
Single and multiple inheritance: files 139 to 141
Last class covered constructors, instance variables and encapsulation, files 123 to 138, and this class went on to inheritance. Inheritance is very simple, the instructor said: there is one class, a father, and one class, a son, and the father gives something to the son. The deck's definition, which the instructor read out:
Inheritance lets a class (child/subclass) reuse attributes and methods of another class (parent/base). It promotes code reuse, organization, and models real-world relationships.
There are almost five types, the instructor said: single, one parent and one child; multiple, two parents; multilevel, a chain from grandparent to parent to child; hierarchical, one parent with several children; and hybrid, a mix of these. Which one is supported and which one is not? The class took each one with an example, and Python supports all five, as the figure shows.
Single inheritance: file 139. One parent, BaseTest, and one child, LoginTest. There is no extends keyword, the instructor said: the child names its parent in brackets, which the comment on line 8 puts as classSon(classFather). Which one is private and which one is public, the instructor asked about lines 2 and 3: the one with the double underscore, __driver2, is private, and driver is public.
class BaseTest:
driver = "chrome"
__driver2 = "firefox"
def setUp(self):
print("Base is setup!")
# si -> classSon(classFather)
class LoginTest(BaseTest):
def run(self):
self.setUp()
print("Running TC")
t = LoginTest()
t.run()
Base is setup!
Running TC
Question, file 139. How are we able to call self.setUp() on line 11, when LoginTest never defines it?
Worth practising too: add print(self.driver) and print(self.__driver2) at the end of run(). Which of the two works?
Show the answer
Answer. Because LoginTest extends BaseTest: line 9 names the parent in brackets, and the child gets the parent's methods. So line 11 runs setUp() from BaseTest, which prints Base is setup!, and line 12 prints Running TC. The parent can give everything to the child, as the instructor put it, with one catch that the README notes point out, run below: self.driver prints chrome, but self.__driver2 stops with an AttributeError.
class BaseTest:
driver = "chrome"
__driver2 = "firefox"
def setUp(self):
print("Base is setup!")
# si -> classSon(classFather)
class LoginTest(BaseTest):
def run(self):
self.setUp()
print("Running TC")
print(self.driver)
print(self.__driver2)
t = LoginTest()
t.run()
Base is setup!
Running TC
chrome
Traceback (most recent call last):
File "chapter_15_Python_PyTest/ex_18_OOPs_Python/05_Inheritance/139_SI.py", line 18, in <module>
t.run()
File "chapter_15_Python_PyTest/ex_18_OOPs_Python/05_Inheritance/139_SI.py", line 14, in run
print(self.__driver2)
^^^^^^^^^^^^^^
AttributeError: 'LoginTest' object has no attribute '_LoginTest__driver2'. Did you mean: '_BaseTest__driver2'?
A private name does not carry over. Inside LoginTest, Python rewrites self.__driver2 as self._LoginTest__driver2, after the class the line is written in. The parent's variable was stored as _BaseTest__driver2, by the same name mangling as in the last class, so the child does not find it, and Python's hint names the real one. For anything a child class should use, the README notes suggest a single underscore.
self is very similar to the this keyword in Java, the instructor said: Python has no this, it has self, which gives a method access to the object's own functions and variables.
Multiple inheritance: file 140. An APIBase class with one method, and a DBBase class with another. The real question, as the instructor put it:
Question, file 140. Can one class extend APIBase as well as DBBase, both of them?
Show the answer
Answer. Absolutely possible, 100% possible, the instructor said. Line 10 names both parents, and run() uses a method from each: authenticate with the API, connect to the database, then run the test case. Python supports it; Java does not, the instructor said, and JavaScript does not either.
class APIBase:
def api_auth(self):
print("Authenticatin API")
class DBBase:
def db_connect(self):
print("Connecting to the DB")
class TestHybrid(APIBase, DBBase):
def run(self):
self.api_auth()
self.db_connect()
print("Test Case Running.")
tc1 = TestHybrid()
tc1.run()
Authenticatin API
Connecting to the DB
Test Case Running.
The class is called TestHybrid, but this is the multiple-inheritance file, two parents and one child, as the README notes list it. Multiple inheritance is 100% possible in Python because of a concept called MRO, the instructor said, and the deck has it the same way:
Multiple inheritance in Python is supported because we have a concept of MRO, which is method resolution order
Two parents, one method: file 141. Then a confusion, as the instructor put it: what if both parents have a method with the same name? Here both fathers have money(). There is a diamond problem in this case, the instructor said: in Java, a child getting the same money() from two fathers is a confusion, but in Python there is none. The deck explains the rule:
MRO stands for Method Resolution Order. It is the order in which Python searches for a method or attribute when multiple inheritance is used. It defines which parent class method is called first.
Question, file 141. Both fathers have a money() method. When the child calls self.money(), which money will be called?
Worth practising too: what does print([c.__name__ for c in Child.__mro__]), the README notes' line, print for the file as pushed?
Show the answer
Answer. Whoever is first, that money will be called, the instructor said. With Father1 first, the class's first run printed F1 Money, because F1 is present before; with the order swapped, F2 is called. The pushed file lists Father2 first, so it prints Son, then F2 Money. The README notes' line prints ['Child', 'Father2', 'Father1', 'object']: Python looks in Child, then in the parents from left to right, and stops at the first money() it finds.
class Father1:
def money(self):
print("F1 Money")
class Father2:
def money(self):
print("F2 Money")
# MRO method resolution order
class Child(Father2,Father1 ):
def give_money(self):
print("Son")
self.money()
c = Child()
c.give_money()
Son
F2 Money
Both orders, each run with the README notes' line added at the end:
| Line 11 lists | Where Python looks, in order | It prints |
|---|---|---|
Father1, Father2, the class's first run |
Child, Father1, Father2, object |
F1 Money |
Father2,Father1, as pushed |
Child, Father2, Father1, object |
F2 Money |
Multilevel, hierarchical and hybrid: files 142 to 145
C.__mro__, printed by file 144 with one line added, and the found method is the file's real first line of output.Multilevel: file 142. A chain: the grandfather gives to the father, and the father to the son. Here the test suite gives everything to the base test, and the base test to the UI test, so UITest has everything: it has the base test, and it has the test suite.
class TestSuite:
def info(self):
print("This is GF - Step 1")
class BaseTest(TestSuite):
def setup(self):
print("BaseTest - F - Step 2")
class UITest(BaseTest):
def run(self):
self.info()
self.setup()
print("Running Test Case")
test = UITest()
test.run()
This is GF - Step 1
BaseTest - F - Step 2
Running Test Case
The deck gives the three levels a QA use case: TestSuite defines metadata, BaseTest does the setup and teardown, and UITest runs the actual UI test. Is it like an interface? Not an interface, the instructor said: it is like a grandfather giving to a father, and the father to a son. That's it.
Hierarchical: file 143. One father and multiple children: here two, LoginTest and SignupTest, and both of them can access the father's properties.
class BaseTest:
def setup(self):
print("Setup from BaseTest")
class LoginTest(BaseTest):
def run(self):
print("Running Login Test")
class SignupTest(BaseTest):
def run(self):
print("Running Signup Test")
LoginTest().setup()
LoginTest().run()
SignupTest().setup()
SignupTest().run()
Setup from BaseTest
Running Login Test
Setup from BaseTest
Running Signup Test
Each of lines 15 to 18 builds a new object and calls one method on it.
Hybrid: file 144. Do we support hybrid also? Of course, the instructor said: in Python, everything is possible. Hybrid means a mixture of multiple and multilevel, as the comment on line 2 says. One grandfather, Base, gives everything to A and to B, and C gets both, so C has every method.
#Hybrid Inheritance
#A mix of multiple and multilevel inheritance.
class Base:
def base_method(self):
print("Base method")
class A(Base):
def a_method(self):
print("A method")
class B(Base):
def b_method(self):
print("B method")
class C(A, B):
def c_method(self):
print("C method")
obj = C()
obj.base_method()
obj.a_method()
obj.b_method()
obj.c_method()
Base method
A method
B method
C method
This is the diamond shape, as the README notes call it: Base sits above both A and B. The figure at the top of this section follows obj.base_method(): Python looks in C, then A, then B, and finds it in Base, which it checks once, after both. With print([c.__name__ for c in C.__mro__]) added at the end, the file prints ['C', 'A', 'B', 'Base', 'object'] after its four lines.
In the real world: file 145. This is how you use it in your UI tests, the instructor said: a base test with a parameterized constructor and a setup, then a login test and a signup test that both get them from the base test.
class BaseTest:
def __init__(self, browser):
self.browser = browser
def setup(self):
print(f"Launching {self.browser}")
class LoginTest(BaseTest):
def run_test(self):
self.setup()
print("Running login test...")
class SignupTest(BaseTest):
def run_test(self):
self.setup()
print("Running signup test...")
t = LoginTest("chrome")
t.run_test()
t = SignupTest("firefox")
t.run_test()
Launching chrome
Running login test...
Launching firefox
Running signup test...
Neither child writes a constructor: LoginTest("chrome") on line 19 runs BaseTest's __init__, which stores the browser that setup() then prints.
Can we use all these concepts in real time, a learner asked? Yes, the instructor said: in CrewAI, the DeepEval framework, LangChain and LangGraph, everywhere. Classes are going to be used everywhere, and single inheritance too, in UI tests as well as API tests.
Polymorphism and overloading: files 146 to 149
add and its signature were printed by a line added at the end of the file.Now comes the important part, polymorphism, which the instructor described as one function or one object which has many forms. The deck's line:
Polymorphism means one function name, multiple forms/behaviors.
It is done in two ways, method overriding and method overloading. The deck lists overriding as runtime polymorphism, and strikes through overloading, compile time polymorphism, because in Python:
Python does not support method overloading
Hack to achieve it.
Python does not support method overloading by default, in the traditional sense, the instructor said, but there is a hack to achieve it. The class made a folder for each, and the instructor asked:
Question, file 146. Method overloading and method overriding: which one is supported, and which one is not?
Show the answer
Answer. Overloading is not supported by default: the same name with different arguments is not possible, and the only way round it is a default parameter, the instructor said. Overriding is supported, as files 150 and 151 show; files 146 to 149 show why overloading fails, and the way round.
Same name, different arguments: file 146. If you try this, it will give you an error, the instructor said: Python will start crying. The file as pushed keeps the second add commented out, and if you run it, nothing happens: it defines the class and calls nothing.
class MathClass:
def add(self, a,b):
return a+b
# def add(self,a,b,c):
# return a-b-c
Switch lines 5 and 6 on and call add() both ways, and the reason shows:
class MathClass:
def add(self, a,b):
return a+b
def add(self,a,b,c):
return a-b-c
m = MathClass()
print(m.add(3, 4, 5))
print(m.add(3, 4))
-6
Traceback (most recent call last):
File "chapter_15_Python_PyTest/ex_18_OOPs_Python/06_Polymorphism/Method_OverLoading/146_MLoading.py", line 11, in <module>
print(m.add(3, 4))
^^^^^^^^^^^
TypeError: MathClass.add() missing 1 required positional argument: 'c'
The last def wins. Python accepts the second def add: it replaces the first, as the README notes put it, so MathClass keeps only add(self, a, b, c). Defining the two is no error, and the file still prints nothing until a call uses the old form. The two-argument call then stops with a TypeError, because the add that is left needs c. (This add subtracts: 3 - 4 - 5 is -6.)
Default parameters: file 147. The only way to do it is with default parameters, the instructor said: the same function name, but the extra argument has a default value, and if it has a default value, it will work.
class Person:
def say_name(self, name):
print("Hi", name)
def say_name(self, name, lastname="Dutta"):
print("Hi,", name, lastname)
t = Person()
t.say_name("Dutta")
t = Person()
t.say_name("Pramod", "Sharma")
Hi, Dutta Dutta
Hi, Pramod Sharma
Hi, Dutta Dutta, because Dutta is the default name, the instructor said: line 10 passes one name, so lastname takes its default, and line 13 passes both. Here too the first say_name is gone, so both calls run the second. The same function name with a different argument is supported only when you have a default parameter, the instructor said: only then, otherwise not.
A real example: file 148. A math class: the same name, different arguments, but whenever you have an extra argument, you have to give it a default value. The figure at the top of this section follows both calls.
class MathClass:
def add(self, a, b):
return a + b
def add(self, a, b, c=10):
return a + b + c
obj_ref = MathClass()
print(obj_ref.add(3, 4, 5))
print(obj_ref.add(3.14, 4.14))
12
17.28
| Call | Arguments passed | Third parameter | Returns |
|---|---|---|---|
add(3, 4, 5), line 10 |
three | 5, as passed | 12 |
add(3.14, 4.14), line 11 |
two | 10, the default | 17.28 |
What is the use of overloading? The same add can work with two variables and with three, the instructor said.
Question, file 148. Will it always call the second method?
Show the answer
Answer. It depends on the arguments, the instructor said: give three, and it uses them; give two, and c takes its default value. Run, both calls go to the second add, because it is the only add left: printed at the end of the file, vars(MathClass) holds one add, with the signature (self, a, b, c=10). What the arguments decide is c.
An interview question: file 149.
Interview question, file 149. Is this valid code or not? And if it is, what is the output?
Worth practising too: what does t.make_http_request("google.com") print?
Show the answer
Answer. Absolutely valid, the instructor said, because default parameters are allowed in method overloading: the same name, with just different parameters. The second make_http_request replaces the first, and line 11 passes both arguments, so the file prints the line with auth: Hi, Lets make the HTTP request with auth google.com admin. With the URL alone, the same method runs with auth at its default, None: Hi, Lets make the HTTP request with auth google.com None.
class Browser:
def make_http_request(self, url):
print("Hi, Lets make the HTTP request without auth", url)
def make_http_request(self, url, auth=None):
print("Hi, Lets make the HTTP request with auth", url, auth)
t = Browser()
t.make_http_request("google.com","admin")
Hi, Lets make the HTTP request with auth google.com admin
Method overriding: files 150 and 151
Overriding only happens when a parent class has a method and a child extends the same method, the instructor said: it always comes with inheritance, and it means the son can change the method. The deck, under the heading Method Overriding (Most Common Polymorphism):
A child class redefines a method from the parent class.
Question, file 150. We create t and call t.run(). Will it call this one or this one, BaseTest's run() or LoginTest's?
Show the answer
Answer. Whoever's object is there, that run() will be called, the instructor said. With t = LoginTest(), the answer was the login test's run(); the file as pushed builds a BaseTest on line 10, so it calls the first one: Running the Base Test.
class BaseTest:
def run(self):
print("Running the Base Test")
class LoginTest(BaseTest):
def run(self):
print("Runnning Login Test")
t = BaseTest()
# t = LoginTest()
t.run()
Running the Base Test
With line 10 switched off and line 11 on, the child's run() answers:
class BaseTest:
def run(self):
print("Running the Base Test")
class LoginTest(BaseTest):
def run(self):
print("Runnning Login Test")
# t = BaseTest()
t = LoginTest()
t.run()
Runnning Login Test
In Hindi there is a saying, jiski lathi, uski bhains, the instructor said, something like whoever has the stick, has the cow: whichever object is created, that run() is called.
One more example: file 151. The same case: a test suite with info(), a base test with setup() and run(), and a login test and an API test that each have a run() of their own.
class TestSuite:
def info(self):
print("Test suite information")
class BaseTest(TestSuite):
def setup(self):
print("Base setup")
def run(self):
print("Base test execution")
class LoginTest(BaseTest):
def run(self): # overriding
print("Login test execution")
class APITest(BaseTest):
def run(self): # overriding
print("API test execution")
# t = LoginTest()
# t = APITest()
t = BaseTest()
t.run()
Base test execution
Create a base test, and it runs the base test's own run(); create a login test or an API test, and it runs that class's code, as the instructor showed:
| Object built | Method that runs | It prints |
|---|---|---|
BaseTest(), line 23 as pushed |
BaseTest.run |
Base test execution |
LoginTest(), line 21 switched on |
LoginTest.run, the override |
Login test execution |
APITest(), line 22 switched on |
APITest.run, the override |
API test execution |
This is the concept of method overriding, the instructor said: a small concept, not difficult at all. The instructor pushed the code here, files 139 to 151, and the class took a 10-minute break.
Abstraction with ABC: files 152 to 154
In OOP, the last important concept is abstraction, as the instructor put it. It sounds very similar to encapsulation, but it is not. The deck's two lines, which the instructor read out almost word for word:
Abstraction in Python is a fundamental concept in object-oriented programming.
focuses on hiding complex implementation details while exposing only the essential features of an object.
Abstraction means a few things are hidden: only the important details are shown, and the rest is hidden. The difference from encapsulation is very simple, the instructor said: encapsulation hides the variables, the instance variables, within the class, and abstraction hides another class.
In Python, abstraction is done with a decorator, abstract method, which is very different from Java and JavaScript, the instructor said; they have not made it difficult, it is super easy. The deck's three steps:
1. Import the
ABCclass and theabstractmethoddecorator from theabcmodule.2. Define a class that inherits from
ABC.3. Use the
@abstractmethoddecorator to define abstract methods
A first example: file 152. The comments at the top of the file are the class's own picture: a car with a key, private and public members, and tyres, all of these are encapsulation, the instructor said, but the gearbox and the engine we want to hide. Then the recipe: import ABC and abstractmethod; the class you want as an abstraction, here Animal, inherits ABC; and the method you want abstract is marked with the decorator. That method is incomplete, and anyone who inherits the class has to complete it. Here Dog completes sound().
# Abstraction
# Hide the details and show what is required.
# Car - with key _ __private, tyres -> public,
# Car -> multiple - Engine, GearBox
# Car -> driver -> Engine, gearbox?
from abc import ABC, abstractmethod
class Animal(ABC):
def __init__(self,name):
self.name = name
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Bark!")
dog = Dog("PP")
dog.sound()
Bark!
An incomplete loan: file 153. To relate, the instructor gave a hypothetical person, Amit, whose father has a loan but has not given it: that is the pass on line 9. You cannot create an empty function, so you write pass, which means not completed as of now. Who is going to give this loan? If you inherit from the father, you have to give it, the instructor said: it is transferred to the children. It looks like we are hiding something, but what abstraction really means is that some things the father has done are incomplete in nature, and you have to complete them.
from abc import ABC,abstractmethod
class Father(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def loan(self):
pass
class Amit(Father):
def loan(self):
print("Giving the 50K loan")
amit = Amit("AMIT SHARMA")
amit.loan()
Giving the 50K loan
A real example: file 154. A browser manager that inherits from ABC and has two methods, the instructor said: one abstract and incomplete, start(), and one complete, stop(). If you extend it, you have to complete start(), because an abstract method is something incomplete.
Question, file 154. start() is incomplete in BrowserManger. Who has to complete it?
Worth practising too: a FirefoxBrowser class that extends BrowserManger and leaves start() out. What happens when you build one?
Show the answer
Answer. The Chrome browser has to complete it, the instructor said: ChromeBrowser extends BrowserManger, so it writes start(), and it gets the complete stop() as it is. A class that leaves start() out cannot be built, as the README notes show with this very FirefoxBrowser, run below: TypeError: Can't instantiate abstract class FirefoxBrowser without an implementation for abstract method 'start'. Building BrowserManger() itself fails the same way.
from abc import ABC, abstractmethod
class BrowserManger(ABC):
@abstractmethod
def start(self):
pass
def stop(self):
print("Stop command, common")
class ChromeBrowser(BrowserManger):
def start(self):
# t = ChromeDriver()
print("We are starting the chrome")
tc = ChromeBrowser()
tc.start()
tc.stop()
We are starting the chrome
Stop command, common
The README notes' FirefoxBrowser, added at the end of the file:
from abc import ABC, abstractmethod
class BrowserManger(ABC):
@abstractmethod
def start(self):
pass
def stop(self):
print("Stop command, common")
class ChromeBrowser(BrowserManger):
def start(self):
# t = ChromeDriver()
print("We are starting the chrome")
tc = ChromeBrowser()
tc.start()
tc.stop()
class FirefoxBrowser(BrowserManger):
pass
FirefoxBrowser()
We are starting the chrome
Stop command, common
Traceback (most recent call last):
File "chapter_15_Python_PyTest/ex_18_OOPs_Python/07_Abstraction/154_REAL_Example.py", line 25, in <module>
FirefoxBrowser()
TypeError: Can't instantiate abstract class FirefoxBrowser without an implementation for abstract method 'start'
Hiding the details: files 155 and 156
How are we hiding, then? The instructor showed it with a car. A gearbox, which comes from ABC, with a setGear() method; an engine, with start() and stop(); and a car that gets from the engine as well as the gearbox, so it has to implement all of them, plus a drive() function that starts, sets the gear and stops.
from abc import ABC, abstractmethod
class GearBox(ABC):
@abstractmethod
def setGear(self):
pass
class Engine:
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Engine,GearBox):
def start(self):
print("Starting")
def stop(self):
print("Stop")
def setGear(self):
print("Gearbox is ready")
def drive(self):
self.start()
self.setGear()
self.stop()
tesla = Car()
tesla.drive()
Starting
Gearbox is ready
Stop
Question, file 155. If I show you only this code, the car's methods and the call to drive(), do you know that an engine or a gearbox also exists?
Show the answer
Answer. No. You can see a start, a stop and a set-gear function, but not where they come from: the Engine and GearBox code is completely hidden, and you can keep it anywhere, the instructor said. Hide more and show only the call on lines 36 and 37, and you will never know. That is abstraction.
Engine does not inherit ABC. Line 9 is class Engine:, so its two @abstractmethod marks are not checked: the decorator works only in a class that inherits ABC, as the README notes point out, which is step 2 of the deck's three. The file prints the same, because Car writes all three methods. But an Engine can still be built, and its start() quietly returns None, while GearBox, which inherits ABC, cannot be built. Lines added after line 37:
from abc import ABC, abstractmethod
class GearBox(ABC):
@abstractmethod
def setGear(self):
pass
class Engine:
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Engine,GearBox):
def start(self):
print("Starting")
def stop(self):
print("Stop")
def setGear(self):
print("Gearbox is ready")
def drive(self):
self.start()
self.setGear()
self.stop()
tesla = Car()
tesla.drive()
print(Engine().start())
GearBox()
Starting
Gearbox is ready
Stop
None
Traceback (most recent call last):
File "chapter_15_Python_PyTest/ex_18_OOPs_Python/07_Abstraction/155_Hide_Abs.py", line 39, in <module>
GearBox()
TypeError: Can't instantiate abstract class GearBox without an implementation for abstract method 'setGear'
With line 9 as class Engine(ABC):, the car drives exactly as before, and now an Engine cannot be built either:
from abc import ABC, abstractmethod
class GearBox(ABC):
@abstractmethod
def setGear(self):
pass
class Engine(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Engine,GearBox):
def start(self):
print("Starting")
def stop(self):
print("Stop")
def setGear(self):
print("Gearbox is ready")
def drive(self):
self.start()
self.setGear()
self.stop()
tesla = Car()
tesla.drive()
Engine()
Starting
Gearbox is ready
Stop
Traceback (most recent call last):
File "chapter_15_Python_PyTest/ex_18_OOPs_Python/07_Abstraction/155_Hide_Abs.py", line 38, in <module>
Engine()
TypeError: Can't instantiate abstract class Engine without an implementation for abstract methods 'start', 'stop'
A test case runner: file 156. One more example: an Excel reader, a browser and a test case runner. The runner is the last two lines of the file, and this is what they print:
tc1 = TC1()
tc1.runTc()
Starting
readFromExcel is ready
Stop
If I show you only this part, you will never know that there is an Excel reader or a browser, the instructor said: you only see that a test case is running. They are in lines 1 to 32; lines 33 to 46 are empty.
from abc import ABC, abstractmethod
class ExcelReader(ABC):
@abstractmethod
def readFromExcel(self):
pass
class Browser(ExcelReader):
@abstractmethod
def startBrowser(self):
pass
@abstractmethod
def stopBrowser(self):
pass
class TC1(Browser):
def startBrowser(self):
print("Starting")
def stopBrowser(self):
print("Stop")
def readFromExcel(self):
print("readFromExcel is ready")
def runTc(self):
self.startBrowser()
self.readFromExcel()
self.stopBrowser()
ExcelReader inherits ABC and leaves readFromExcel() incomplete, and Browser extends it with two more incomplete methods. So TC1, the test case, has to complete all three: printed at the end of the file, sorted(Browser.__abstractmethods__) gives ['readFromExcel', 'startBrowser', 'stopBrowser'], the three methods the README notes list for the child to write.
Static variables and static methods: files 157 and 158
One more concept, a small one, so as not to make it too complex today, the instructor said: static. Static is absolutely the same as in Java: it belongs to the class, so it will be the same for all object references, and whatever is common between all object references becomes static. Lines 1 to 4 of file 157 say it in comments.
Question, file 157. In a class for the AI Tester Blueprint, what is common in all of us?
Worth practising too: after AITB.mentor = "New", what do s1.mentor and s2.mentor give? And after s1.mentor = "Own"?
Show the answer
Answer. The course name and the mentor: they are common, so they are static in nature, the instructor said. In file 157 they are lines 7 and 8, written in the class body with no keyword. The name is different for every student, so it goes through self.name in the constructor. AITB.mentor = "New" changes the one copy, so s1.mentor and s2.mentor both give New; s1.mentor = "Own" gives s1 a mentor of its own, while s2.mentor and AITB.mentor stay New, as the README notes point out.
# Static = Belong to class
#. it will be same for all objects ref.
# whatever is common b/w all objects ref
# it become static
class AITB:
statcousreName = "AITB"
mentor = "PrrammodDutta"
def __init__(self,name):
self.name = name
def display(self):
print("Hi,", self.name,"Your Mentor is " + AITB.mentor)
@staticmethod
def display2():
print("Static Method!")
Lines 20 and 21 build two students, s1 and s2, each from a first name, and there is no new keyword in Python. Lines 23 and 24 call display() on each: each prints Hi, the student's own name, then Your Mentor is PrrammodDutta, so the name is different and the mentor is the same. Line 26 calls display2() on the class and prints Static Method!.
| Read | Where it lives | Result |
|---|---|---|
s1.name, s2.name |
on each object, set in __init__ |
two different names |
s1.mentor, s2.mentor, AITB.mentor |
on the class: one copy | PrrammodDutta, all three |
AITB.display2() |
on the class, no object | Static Method! |
The deck puts it the same way:
Static (also called class) variables are shared by all objects of a class. They belong to the class itself, not to any particular object instance.
You do not need a static keyword, the instructor said: have we added any keyword? No. By default it becomes static, and there is no static keyword in Python. Python is a very strange language, isn't it, the instructor asked. For a method there is a way: @staticmethod, on line 16, and display2() takes no self. A static method call does not need an object: the class name, dot, the method.
A real example: file 158. An Excel reader and a MySQL connection, each with a static method, and test cases that call them directly, without creating an object.
class ExcelReader:
@staticmethod
def readExcelFile():
print("Reading from Excel")
class MYSQLDBConnection:
@staticmethod
def readMySQLFile():
print("Reading from MySQL")
class TC1:
def runTC(self):
ExcelReader.readExcelFile()
MYSQLDBConnection.readMySQLFile()
print("Hi")
class TC2:
def runTC(self):
ExcelReader.readExcelFile()
MYSQLDBConnection.readMySQLFile()
print("Hi")
tc1 = TC1()
tc2 = TC1()
tc1.runTC()
tc2.runTC()
Reading from Excel
Reading from MySQL
Hi
Reading from Excel
Reading from MySQL
Hi
Line 28 builds a TC1. tc2 = TC1() makes a second TC1, so TC2 is defined but never runs, as the README notes point out. The output cannot show it, because the two runTC() methods are the same: with line 28 as tc2 = TC2(), the file prints the same six lines.
Tasks and announcements
- Exercises up to 158, before tomorrow's class. Take out some time today and practise up to exercise 158, the instructor said: when you come back to tomorrow's class, the instructor wants to make sure the 158 exercises are done. Meeti was asked to add the task.
- Your own GitHub repository. The class opened with a look at the batch's GitHub repositories. Push all your work up to the OOP concepts in Python to your own repository: it is very, very important, the instructor said, and if possible, please do it. Even if you have missed four or five sessions, or have not pushed, that is fine, but creating the repository and replicating the work is very important.
- Tomorrow's class runs as usual. There will be a class tomorrow, Sunday: no cancellation, and no holiday. It covers the remaining topics: exceptions, modules, a little about file IO, packages, collections and pytest, which are needed further on. The deck's 14 November section ends with the same list.
- This week, then next week. This week's target is to finish Python: the rest of OOP, plus extra concepts, and part of pytest. Next week the class starts CrewAI, LangChain and LangGraph, and last, DeepEval. All four are about Python, and without Python and pytest practised they will be very difficult, the instructor said. The course is about to finish, in the next two or three weeks, and the focus will mostly be these four.
- What level of Python? The level the class is discussing, the instructor answered a learner: LLM evaluation needs Python and pytest, and what the class is learning is more than enough.
- Doubts: the doubt thread has already been created.
- Tester Town. The instructor showed Tester Town. AI 4x has a private group there, created specially for the batch, next to a public chat and a place for doubts, and there is a game side with QA battles, daily battles for interview practice. Go to your own group, say hi, and share there what you learned today and your repository. Follow the guidelines, the instructor said: it is public, and your LinkedIn and everything is visible to everyone. The instructor and Meeti will be there, and anyone who does not have access will get it soon.
Task: exercises up to 158. Practise every exercise up to 158 before tomorrow's class, and push your Python work, up to the OOP concepts, to your own GitHub repository.
Show the answer
Answer. Files 139 to 158 are all on this page, each with what it prints. Write each one yourself, run it, and compare your output with the page, then push them to your own repository.