(This page has no text content)
73 Python Object Oriented Programming Exercises Volume 2
73 Python Object Oriented Programming Exercises Volume 2 Edcorner Learning Table of Contents Introduction Module 1 Class Method - Decorator Module 2 Static Method - Decorator Module 3 Special Methods Module 4 Inheritance Module 5 Abstract Classes Module 6 Miscelleanuoes Exercises
Introduction Python is a general-purpose interpreted, interactive, object- oriented, and a powerful programming language with dynamic semantics. It is an easy language to learn and become expert. Python is one among those rare languages that would claim to be both easy and powerful. Python's elegant syntax and dynamic typing alongside its interpreted nature makes it an ideal language for scripting and robust application development in many areas on giant platforms. Python helps with the modules and packages, which inspires program modularity and code reuse. The Python interpreter and thus the extensive standard library are all available in source or binary form for free of charge for all critical platforms and can be freely distributed. Learning Python doesn't require any pre- requisites. However, one should have the elemental understanding of programming languages. This Book consist of 73 python Object Oriented Programming coding exercises to practice different topics. In each exercise we have given the exercise coding statement you need to complete and verify your answers. We also attached our own input output screen of each exercise and their solutions. Learners can use their own python compiler in their system or can use any online compilers available. We have covered all level of exercises in this book to give all the learners a good and efficient Learning method to do hands on python different scenarios.
Module 1 Class Method - Decorator 1. Using the classmethod class (do it in the standard way) implement a class named Person that has a class method named show_details() which displays the following text to the console: 'Running from Person class.' Try to pass the class name using the appropriate attribute of the Person class. In response, call the show_details() class method. Expected result: Running from Person class. 2. Using the classmethod class (do it in the standard way) implement a class named Person that has a class method named show_details() which displays the following text to the console: 'Running from Container class.' Try to pass the class name using the appropriate attribute of the Person class.
In response, call the show_details() class method. Expected result: 'Running from Container class.' 3. The Container class is given. Create an instance of this class named container and call the show_details( ) method from this instance. Expected result: Running from Container class. class Container: @classmethod def show_details(cls):
print(f'Running from {cls.__name__} class.') 4. Implement a class named Person which has a class attribute named instances as an empty list. Then, each time you create an instance of the Person class, add it to the Person.instances list (use the init () method for this). Also implement a class method called count_instances( ) that returns the number of Person objects created (the number of items in the Person.instances list). Create three instances of the Person class. Then call the count_instances( ) class method and print result to the console. Expected result: 3
(This page has no text content)
5. A class named Person is given. Modify the _init() method so that you can set two instance attributes: firstname and lastname (bare attributes, without any validation). Create two instances of the Person class. Then call the count_instances() class method and print result to the console. Expected result: 2 class Person: instances = [] def __init__(self): Person.instances.append(self) @classmethod def count_instances(cls): return len(Person.instances)
(This page has no text content)
Module 2 Static Method - Decorator 6. Define a Container class that has a static method (use the staticmethod class - do it in the standard way) named get_current_time( ) returning the current time in the format ‘ %H : %M : %S ' , e.g. '09:45:10' . Tip: Use the built-in time module. Solution: import time class Container: def get_current_time(): return time.strftime('%H:%M:%S', time.localtime()) get_current_time = staticmethod(get_current_time) 7. Define a Container class that has a static method (use the @staticmethod decorator) named get_current_time() returning the current time in the format '%h:%m:%s' , e.g. '09:45:10' .
Tip: Use the built-in time module. Solution : import time class Container: @staticmethod def get_current_time(): return time.strftime('%H:%M:%S', time.localtime()) 8. Complete the implementation of the Book class. In the _init_ ( ) method, set the bare attributes of the instance with names: • title • author • book_id Set the instance book_id attribute using the uuid module. Exactly the
uuid. uuid4( ) function from this module. An example of using this function: import uuid str(uuid.uuid4().fields[-1])[: 6] Returns a 6-element string. This will be the value of the bookjd attribute. Using the above code, create a static method of the Book class (use the @staticmethod decorator) called get_id() L which will generate a 6- digit str object (the value of the bookjd field). Then create an instance of the class named bookl with the following arguments: • title=' Python Object Oriented Programming Exercises Volume 2' • author='Edcorner Learning' In response, print all the _dict_ attribute keys of book1 to the console. Expected result: dict_keys(['book_id', 'title', 'author']) import uuid class Book: def __init__(self, title, author): pass
Solution: import uuid class Book: def __init__(self, title, author): self.book_id = self.get_id() self.title = title self.author = author @staticmethod def get_id(): return str(uuid.uuid4().fields[-1])[:6] book1 = Book(' Python Object Oriented Programming Exercises Volume 2', 'Edcorner Learning') print(book1.__dict__.keys())
9. The Book class is implemented. Add a _repr_( ) method to the Book class that represents an instance of this class (see below). Then create an instance of the class named book 1 passing the following arguments: • title= ‘Python Object Oriented Programming Exercises Volume 2' • author='Edcorner Learning' In response, print the instance book1 to the console. Expected result: Book(title=' Python Object Oriented Programming Exercises Volume 2', author='Edcorner Learning') import uuid class Book: def __init__(self, title, author): self.book_id = self.get_id()
self.title = title self.author = author @staticmethod def get_id(): return str(uuid.uuid4().fields[-1])[:6] Solution: import uuid class Book: def __init__(self, title, author): self.book_id = self.get_id() self.title = title self.author = author def __repr__(self): return f"Book(title='{self.title}', author='{self.author}')" @staticmethod def get_id(): return str(uuid.uuid4().fields[-1])[:6] book1 = Book(' Python Object Oriented Programming Exercises Volume 2', author='Edcorner Learning')
Module 3 Special Methods 10. Define a Person class that takes two bare attributes: fname (first name) and Iname (last name). Then implement the _repr_ ( ) special method to display a formal representation of the Person object as shown below: [IN]: person = Person('John', 'Doe') [IN]: print(person) [OUT]: Person(fname='John', lname=’Doe’) Create an instance of the Person class with the given attributes: fname = 'Mike' • lname = 'Smith' and assign it to the variable person. In response, print the person instance to the console. Expected result: Person(fname='Mike’, lname='Smith')
Solution: 11. The Person class is implemented. Add a special method _str_ () to return an informal representation of an instance of the Person class. Example: [IN]: person = Person('Mike', 'Smith') [IN]: print(person)
First name: Mike Last nane: Smith Then create an instance named person with the following values: • fname = 'Edcorner’ • lname = 'Learning' In response, print the person instance to the console. Expected result: First name: Edcorner Last name: Learning class Person: def __init__(self, fname, lname): self.fname = fname self.lname = lname def __repr__(self): return f"Person(fname='{self.fname}', lname='{self.lname}')"
Comments 0
Loading comments...
Reply to Comment
Edit Comment