75 Python Object Oriented Progr - Learning, Edcorner
75 Python Object Oriented Progr - Learning, Edcorner
Object Oriented
Programming Exercises
Volume 1
75 Python
Object Oriented
Programming Exercises
Volume 1
Edcorner Learning
Table of Contents
Introduction
Module 1 Local Enclosed Global Built-In Rules
Module 2 Namespaces and Scopes
Module 3 Args and Kwargs
Module 4 Classes
Module 5 Classes Attributes
Module 6 Instance Attributes
Module 7 The _Init_() Method
Module 8 Visibility of Variables
Module 9 Encapsulation
Module 10 Computed Attributes
Introduction
1. The stock_info( ) function is defined. Using the appropriate attribute of the stock_info( )
function, display the names of all arguments to this function to the console.
An example of calling the function:
print(stock_info('ABC', 'USA', 115, '$'))
Company: ABC
Country: USA
Price: $ 115
1
Solution:
import builtins
help(builtins.sum)
print(builtins.sum([-4, 3, 2]))
print(counter)
Solution:
Expected result:
110
..........
def display_info(number_of_updates=1):
counter = 100
dot_counter = ''
def update_counter():
counter += 1
dot_counter += '.'
[update_counter() for _ in range(number_of_updates)]
print(counter)
print(dot_counter)
Solution:
Module 2 Namespaces and Scopes
6. Import the built-in datetime module and display the namespace of this module (sorted
alphabetically) as given below.
Tip: Use the _dict_ attribute of the datetime module.
Expected result:
MAXYEAR
MINYEAR
_builtlns_
_cached_
_doc_
_file_
_loader_
_name_
_package_
_spec_
date
datetime
datetime_CAPI
sys
time
timedelta
timezone
tzinfo
Solution:
7. The Product class is given below. Display the namespace (value of the _dict_ attribute) of
this class as shown below.
Expected result:
__module__
__init__
__repr__
get_id
__dict__
__weakref__
__doc__
import uuid
class Product:
def __init__(self, product_name, price):
self.product_id = self.get_id()
self.product_name = product_name
self.price = price
def __repr__(self):
return f"Product(product_name='{self.product_name}', price={self.price})"
@staticmethod
def get_id():
return str(uuid.uuid4().fields[-1])[:6]
8. The Product class is specified. An instance of this class named product was created. Display
the namespace (value of the _dict_ attribute) of this instance as shown below.
Expected result:
{'product_name': 'Mobile Phone1, 'product_id': '54274', 'price': 2900}
import uuid
class Product:
def __init__(self, product_name, product_id, price):
self.product_name = product_name
self.product_id = product_id
self.price = price
def __repr__(self):
return f"Product(product_name='{self.product_name}', price={self.price})"
product = Product('Mobile Phone', '54274', 2900)
Solution:
Module 3 Args and Kwargs
9. Implement a function called stick( ) that takes any number of bare arguments and return an
object of type str being a concatenation of all arguments of type str passed to the function with
the '#' sign (see below).
Example:
[IN]: stick('sport', 'summer', 4, True)
[OUT]: 'sport#summer’
As an answer call the stick( ) function in the following ways (print the result to the console):
• stick('sport', 'summer')
• stick(3, 5, 7)
stick(False, 'time'. True, 'workout', [], 'gym')
Expected result:
Sport#sumer
time#workout#gym
Solution:
10. Implement a function called dispiay_info() which prints the name of the company (as shown
below) and if the user also passes an argument named price , it prints the price (as shown
below).
Example I:
[IN]: dlsplay_info(company='Amazon')
Company name: Apple
Example II:
[IN]: display_info(company='Amazon', price=1140)
Company name: Amazon Price: $ 1140
In response, call display_info() as shown below:
display_info(company='CD Projekt', price=100)
Expected result:
Company name: CD Projekt Price: $ 100
def display_info(company, **kwargs):
pass
Solution:
Module 4 Classes
11. Create the simplest class in Python and name it Vehicle.
Tip: Use the pass statement.
Solution:
class Vehicle:
pass
12. Create the simplest Python class named Phone and display its type to the console.
Expected result:
<class ‘type’>
Solution:
class Phone:
pass
print(type(Phone))
13. Create a class named Vehicle and add the following documentation:
"""This is a Vehicle class."""
Solution
class Vehicle:
class Container:
"""This is a Container class."""
exercise
class Container:
"""This is a Container class."""
Solution:
class Container:
"""This is a Container class."""
print(Container.__module__)
Note: The solution that the user provides is in a file named exercise.py, while the
checking code (which is invisible to the user) is executed from a file named evaluate.py
from the level where the Container class is imported. Therefore, instead of the name of
the module _main_ , the response will be the name of the module in which this
class is implemented, exercise in this case.
Expected result:
<class 'exercise.Container’>
class Container:
"""This is a Container class."""
Solution:
class Container:
"""This is a Container class."""
container = Container()
print(type(container))
18. The implementation of the Container class is given:
class Container:
"""This Is a Container class.
Create an instance of the Container class and assign to the container variable. Then print the
_class _ attribute value of the container instance.
Note: The solution that the user provides is in a file named exercise.py, while the checking code
(which is invisible to the user) is executed from a file named evaluate.py from the level where
the Container class is imported. Therefore, instead of the name of the module _main_ ,
the response will be the name of the module in which this class is implemented, exercise in this
case.
Expected result:
<class 'exercise.Container’>
class Container:
"""This is a Container class."""
Solution:
class Container:
"""This is a Container class."""
container = Container()
print(container.__class__)
19. Define a simple class named Model. Then create an instance of this class named
model.
Using the built-in function isinstance( ) check if the model is an instance of the Model
class. Print the result to the console.
Expected result:
True
20. Define two empty classes named:
• Model
• View
Then create two instances (one for each class):
• model for the Model class
• view for the View class
Using the built-in function isinstance( ) check whether the model and view objects are instances
of the Model class. Print the result to the console.
Expected result:
True
False
21. Two empty classes are defined:
• Model
• View
class View:
pass
object1 = Model()
object2 = [Model(), Model()]
object3 = {}
22. Implement an empty class named Container. Then create an instance of this class named
container. In response, display the type of dictionary attribute _dict_ for the Container class and
for the container instance.
Expected result:
<class ‘mappingproxy’>
<class 'dict’>
24. Implement a class named Brandname. In the Phone class, define a class attribute
named brand and set its value to ‘Amazon’. Then, using dot notation and print ( )
function, display the value of the brand attribute of the Phone class to the console.
Expected result:
Amazon
25. Implement a class named Phone. In the Phone class, define two class attributes with
names:
• brand
• model
and set their values to:
• 'Apple'
• ‘iPhone X'
Then use the built-in functions getattr() and print () to display the values of the given attributes of
the Phone class to the console as shown below.
Expected result:
Apple
iPhone X
26. A class named Phone is defined below. Using dot notation, modify the value of the
attributes:
• brand to 'Samsung'
• model to 'Galaxy'
In response, print the values for the brand and model attributes to the console as shown below.
Expected result:
brand: Samsung
model: Galaxy
class Phone:
brand = 'Apple'
model =
'iPhone X'
27. A class named Laptop is defined below. Using the setattr( ) built-in function modify
the value of attributes:
• brand to 'Acer'
• model to 'Predator'
In response, using the built-in function getattr() and print() .print the values of the brand
and model attributes to the console as shown below.
Expected result:
brand: Acer
model: Predator
class Laptop:
brand = 'Lenovo'
model = 'ThinkPad'
28. Implement a class named OnlineShop with the class attributes set appropriately:
• Sector to the Value 'electronics'
• sector_code to the value 'ele'
• is_public_company to the value False
Then, using dot notation, add a class attribute called country and set its value to 'usa' . In
response, print the user-defined OnlineShop class attribute names as shown below.
Expected result:
['sector', 'sector_code', 1is_public_company','country']
29. A class named OnlineShop was defined with the class attributes set accordingly:
• Sector to the Value 'electronics'
• sector_code to the value 'ele'
• is_public_company to the value False
Using the del statement remove the class attribute named sector_code. In response, print the
rest of the user-defined OnlineShop class attribute names as a list as shown below.
Expected result:
[ ' sector',‘is_public_company’]
class OnlineShop:
sector = 'electronics'
sector_code = 'ELE'
is_public_company = False
30. A class named OnlineShop was defined with the class attributes set accordingly:
• Sector to the Value 'electronics'
• sector_code to the value 'ele'
• is_public_company to the value False
Using the builtin deiattrQ function remove the class attribute sector_code. In response, print the
rest of the user-defined OnlineShop class attribute names as a list as shown below.
Expected result:
[‘sector','is_public_company’]
class OnlineShop:
sector = 'electronics'
sector_code = 'ELE'
is_public_company = False
31. A class named OnlineShop was defined with the class attributes set accordingly:
• Sector to the Value 'electronics'
• sector_code to the value 'ele'
• is_public_company to the value False
Display all user-defined OnlineShop class attribute names with their values as shown below.
Expected result:
sector -> electronics
32. A class named OnlineShop was defined with the class attributes set accordingly:
• Sector to the Value 'electronics'
• sector_code to the value 'ele'
• is_public_company to the value False
Outside of the class, implement a function called describe_attrs() that displays the names of all
user-defined class attributes and their values as shown below. In response, call the
describe_attrs() function.
Expected result:
sector = 'electronics'
sector_code = 'ELE'
is_public_company = False
Solution:
class OnlineShop:
sector = 'electronics'
sector_code = 'ELE'
is_public_company = False
def get_sector():
return OnlineShop.sector
Expected result:
Floor number: 3
Area: 100
Module 6 Instance Attributes
35. The Book class is defined. Create an instance of the Book class named book.
Display the value of the _dict_ attribute for the book instance. Then
assign two attributes to the book instance:
• author to the Value 'Dan Brown'
• title to the value ' Inferno '
In response, display the _dict_ attribute for the book instance again.
Expected result:
{}
{'author': 'Dan Brown','title','Inferno'}
class Book:
language = 'ENG'
is_ebook = True
36. The Book class is defined. Create two instances of the Book class named
book_1 and book_2. Then assign instance attributes to these objects (using dot notation)
as follows:
• to object book_1:
Expected result:
{'author': 'Edcorner Learning', 'title': 'Python Programming Exercises'}
{'author': 'Edcorner Learning', 'title': 'Python OOPS Exercises',
'year_of_publishment': 2021}
class Book:
language = 'ENG'
is_ebook = True
37. The Book class is defined. Two instances of the Book class named book_1 and
book_2 was created. Then the instance attributes were assigned to these objects (using
the dot notation), respectively:
• to object book_1:
• author = 'Dan Brown'
• title = 'Inferno'
to object book_2:
title = 'The Da Vinci Code'
• year_of_publishment = 2003
Then a books list was created. Create a loop to list all the attributes of the book_l and
book_2 instances with their values as shown below (separate each instance with a line
of 30 1 - ' characters as shown below).
Expected result:
author -> Dan Brown
title -> Inferno
------------------------------
author -> Dan Brown
title -> The Da Vinci Code
year_of_publishment -> 2003
-----------------------------
class Book:
language = 'ENG'
is_ebook = True
book_1 = Book()
book_2 = Book()
class Book:
language = 'ENG'
is_ebook = True
40. The Book class is defined. Implement a method named set_title() that sets an instance
attribute named title. Before setting the value, check if it's an object of str type, if not raise a
TypeError with the following message:
'The value of the title attribute must be of str type.'
Then create an instance of the Book class named book and set the title attribute to ' inferno '
using the set_title() method.
In response, print the value of the title attribute of the book instance.
Expected result:
Python OOPS Exercises
class Book:
language = 'ENG'
is_ebook = True
41. The Book class is defined. A method called set_title( ) was implemented that allows you to
set an instance attribute called title. Create an instance of the Book class named book. Then,
using the try ... except ... clause, try using the set_title()method to set the value of the title
attribute to False . In case of a TypeError , print the error message to the console.
Expected result:
The value of the title attribute must be of str type.
class Book:
language = 'ENG'
is_ebook = True
42. Implement a class called Laptop that sets the following instance attributes when creating an
instance:
• brand
• model
• price
Then create an instance named laptop with the following attribute values:
• brand = 'Acer'
model = 'Predator'
price = 5490
Tip: Use the special method init
In response, print the value of the _dict_ attribute of the laptop instance.
Expected result:
{'brand ' :'Acer', 'model': 'Predator1, 'price': 5490}
self.price = price
44. A class called Laptop was implemented.
Implement a method in the Laptop class called display_attrs_with_values() , which displays the
names of all the attributes of the Laptop class with their values as shown below (attribute name -
> attribute value).
Then create an instance named laptop with the following values:
• brand = 'Dell'
model = 'Inspiron'
price = 3699
In response, call display_attrs_with_values( ) method on the laptop instance.
Expected result:
brand - Dell
model - Inspiron
price -3699
class Laptop:
def __init__(self, brand, model, price):
self.brand = brand
self.model = model
self.price = price
45. Implement a class named Vector that takes any number of n-dimensional vector coordinates
as arguments when creating an instance (without any validation) and assign to instance attribute
named components. Then create two instances with following coordinates:
• (1, 2)
• (4, 5, 2)
and assign to variables v7 and v2 respectively.
In response, print the value of the components attribute for v1 and v2 instance as shown below.
Expected result:
V1 -> (1, 2)
v2 -> (4, 5, 2)
46. Implement a class called Bucket that takes any number of named
arguments (keyword arguments - use **kwargs ) when creating an instance.
The name of the argument is the name of the instance attribute, and the
value for the argument is the value for the instance attribute.
Example:
[IN]: bucket = Bucket(apple=3.5)
[IN]: print(bucket. _dict_)
Then create instance named bucket by adding the following attributes with
their values:
• apple = 3.5
• milk = 2.5
• juice = 4.9
• water = 2.5
In response, print the value of _dict_ attribute for the bucket instance.
Expected result:
{'apple': 3.5, 'milk': 2.5, 'juice': 4.9, 'water1: 2.5}
47. Implement a class called Car that sets the following instance attributes when
creating an instance:
• brand
• model
• price
• type_of_car, by default ‘sedan '
Then create an instance named car with the given values:
• brand = 'Opel'
• model = 'Insignia'
• price = 115000
In response, print the value of the _dict_ attribute of the car instance.
Expected result:
brand = 'BMW
• model = 'X3'
• price = 200000
• type_of_car = 'SUV'
In response, print the value of the diet attribute of the car instance.
Expected result:
class Car:
51. Implement a class called Laptop that sets the following instance attributes
when creating an instance:
• brand as a bare instance attribute
• model as a protected attribute
• price as a private attribute
Then create an instance named laptop with the following arguments:
• 'Acer'
• 'Predator'
• 5490
In response, print the value of the _dict_ attribute of the laptop instance.
Expected result:
{'brand': 'Acer', '_model': 'Predator', '_Laptop__price': 5490}
52. A class called Laptop was implemented. Then, an instance of the Laptop
class named laptop was created with the following arguments:
• 'Acer'
• 'Predator'
• 5490
In response, print the value for each instance attribute (on a separate line) of
the laptop instance as shown below.
Expected result:
brand -> Acer
model -> Predator
price -> 5490
class Laptop:
55. Implement a class called Laptop which in the init ( ) method sets the value of
the price
protected attribute that stores the price of the laptop (without any validation).
Then implement a method to read that attribute named get_price() and a
method to modify that attribute named set_price( ) without validation as well.
Then create an instance of the Laptop class with a price of 3499 and follow
these steps:
• using the get_price( ) method print the value of the price protected attribute to
the console
• using the set_price( ) method, set the value of the price protected attribute to
3999
• using the get_price( ) method print the value of the price protected attribute to
th e console
Expected result:
3499
3999
56. A class called Laptop was implemented. Implement a method named
set_price() to modify price attribute that validates the value. Validation checks:
• whether the value is an int or float type, if it is not raise a TypeError with the
following message:
'The price attribute must be an int or float type.'
whether the value is positive, if it is not raise vaiueError
with the following message:
The price attribute must be a positive int or float value.'
Then create an instance of the Laptop class with a price of 3499 and try to set 1
- 3000 ■ to the price using set_price( ) method. If an error is raised, print the
error message to the console. Use a try ... except ... clause in your solution.
Expected result:
The price attribute must be an int or float type.
class Laptop:
def get_price(self):
return self._price
57. A class called Laptop was implemented. The _init_( ) method sets the value
of the price
protected attribute that stores the price of the laptop (without any validation).
Create an instance of the Laptop class with a price of 3499 and try to set the
price to -3000 using the set_price( ) method. If an error is raised, print the error
message to the console. Use a try ... except ... clause in your solution.
Expected result:
The price attribute must be a positive int or float value.
class Laptop:
def get_price(self):
return self._price
def get_price(self):
return self._price
self._price = value
59. Implement a class named Person that has one protected instance attribute
named first_name. Next, implement a method get_first_name( ) which reads the
value of the firstname protected attribute. Then, using the get_first_name( )
method and the property class (do it in the standard way) create a property
named firstname (read-only property).
Create an instance of the Person class and set the firstname attribute to ' john ' .
Print the value of the firstname attribute of this instance to the console.
Expected result:
John
60 . Implement a class named Person that has two instance
protected attributes named first_name and lastname, respectively. Then
implement methods named get_first_name() and get_last_name( ) , which
reads the protected attributes: firstname and lasLname.
Then, using the get_first_name() and get_last_name() methods and the
property class (do it in the standard way) create two properties named
firstname and lastname (read-only properties).
Create an instance of the Person class and set the following attributes:
• firstname to the value 'John'
• lastname to the value 'Dow'
Print the value of the firstname and last_name attribute of this instance
to the console.
Expected result:
John
Dow
61 . Implement a class named Person that has two instance
protected attributes named first_name and lastname, respectively. Then
implement methods named get_first_name() and get_last_name( ) , which
reads the protected attributes: firstname and lasLname.
Then, using the get_first_name() and get_last_name() methods and the
property class (do it in the standard way) create two properties named
firstname and lastname (read-only properties).
Create an instance of the Person class and set the first_name attribute to
■ Dohn ' . Then, using the set_first_name() method, Set new value 'Mike' .
In response, print the value of the first_name attribute to the console.
Expected result:
Mike
62. Implement a class named Person that has two instance protected
attributes named first_name and lastname, respectively. Then implement
methods named get_first_name() and get_last_name( ) , which reads the
protected attributes: firstname and lastname.
Then, using the get_first_name() and get_last_name() methods and the
property class (do it in the standard way) create two properties named
firstname and lastname (read-only properties).
Solution:
class Person:
def get_first_name(self):
return self._first_name
def get_last_name(self):
return self._last_name
def set_last_name(self, value):
self._last_name = value
person.first_name = 'Tom'
person.last_name = 'Smith'
print(person.__dict__)
63. A class named Person was implemented.
Implement the del_first_name() method to remove the firstname protected
attribute.
Then, Using the methods get_first_name() , set_first_name() ,
del_first_name() and the property class (do this in the standard way)
create property named firstname (properties to read, modify and delete).
Create an instance of the Person class named person and assign the
value ' Tom1 to firstname. Use the del_first_name() method to delete the
firstname attribute of the person instance. Display the _dict_ attribute of
the person instance to the console.
Expected result:
{}
``class Person:
Expected result:
{'_name': 'Max'}
65. Implement a class named Pet that has two protected instance attributes:
name and age, respectively. Next implement the methods: name() and age(),
which reads the value of the protected attributes: name and age.
Using the @property decorator, create properties: name and age, respectively
(read-only properties).
Create an instance of the Pet class named pet and set the name attribute to '
Max ' and age to
In response, print the contents of the _dict_ attribute of pet instance to the
console.
Expected result:
{'_name': 'Max', '_age': 5}
66. Implement a class named Pet that has one protected instance attribute
name. Then, using the @property decorator, create a property name (property
to read and modify, without validation).
Create an instance of the Pet class named pet and set the name attribute to
'Max’. Then, using dot notation, modify the value of the name attribute to
'Oscar’.
In response, print the contents of the _dict_ attribute of this instance to the
console.
Expected result:
{'_name': 'Oscar'}
67. Implement a class named Pet that has one protected instance
attribute name. Then, using the @property decorator, create a property
name (property to read and modify, without validation).
Create an instance of the Pet class with the name pet and attributes:
• name = 'Max'
• age = 5
Print the _dict_ attribute of the pet instance to the console. Then modify
the attributes using the dot notation:
• name to the value 'Tom’
• age to the value 8
Again, print the _dict_ attribute of the pet instance to the console again.
Expected result:
{'_name': 'Max', '_age1 : 5}
{'_name': 'Ton', '_age1 : 8}
68. A class called Pet is implemented that has two properties: name and
age (see below). Add validation to the age property at the stage of object
creation and attribute modification:
• the value of the age attribute must be an int type, otherwise raise a
TypeEmor with the following message:
'The value of age must be of type int.’
the value of the age attribute must be positive, otherwise raise valueEmor
with the
following message:
'The value of age must be a positive integer.'
Then try to create an instance of the Pet class named pet and set the
following values:
• 'Max'
• 'seven'
If there is an error, print an error message to the console. Use a try ...
except ... clause your solution.
If there is an error, print an error message to the console. Use a
try ... except . . clause in your solution.
Expected result:
The value of age must be of type Int.
class Pet:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def age(self):
return self._age
@age.setter
def age(self, value):
self._age = value
Solution:
class Pet:
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if not isinstance(value, int):
raise TypeError('The value of age must be of type int.')
if not value > 0:
raise ValueError('The value of age must be a positive
integer.')
self._age = value
try:
pet = Pet('Max', 'seven')
except TypeError as error:
print(error)
except ValueError as error:
print(error)
69. A class called Pet is implemented that has two properties: name and age
(see below). Create an instance of the Pet class with the name pet and attribute
values respectively:
• 'Max'
•7
Then try to modify the value of the age attribute to -10. If there is an error, print
this error message to the console. Use a try ... except ... clause in your solution.
Expected result:
The value of age must be a positive integer.
class Pet:
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if not isinstance(value, int):
raise TypeError('The value of age must be of type int.')
if not value > 0:
raise ValueError('The value of age must be a positive integer.')
self._age = value
Solution:
class Pet:
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if not isinstance(value, int):
raise TypeError('The value of age must be of type int.')
if not value > 0:
raise ValueError('The value of age must be a positive
integer.')
self._age = value
pet = Pet('Max', 7)
try:
pet.age = -10
except TypeError as error:
print(error)
except ValueError as error:
print(error)
70. Implement a class named TechStack that has one protected instance
attribute named tech_names. Then, using the @property decorator,
create a property named tech_names (read, modify, and delete property,
without validation).
Create an instance of the class named tech_stack and the
tech_names attribute value:
• 'python,java,sql'
Print the content of the tech_names attribute. Then, modify this
attribute to value:
• ‘python,sql'
Also print the contents of the tech_names attribute to the console.
Remove the tech_names attribute of the tech_stack instance.
Print the contents of the diet attribute of the tech_stack instance to the
console.
Expected result:
python,java,sql
python,sql
{}
71. Implement a class Game that has a property named level (read and
modify property, defaults to 0). The value of the level attribute should be
an integer in the range [0, 100] . Add validation at the instance creation
and attribute modification stage. If the value is not of the int type, raise a
TypeError with the following message:
'The value of level must be of type int.'
If the value is outside the range [0, 100] , set the exceeded boundary
value (0 or 100 respectively). Then create a list called games consisting of
four instances of the Game class:
games = [GameQ, Game(10), Game(-lO), Game(120)]
Iterate through the games list and print the value of the level attribute for
each instance.
Expected result:
0
10
0
100
Module 10 Computed Attributes
72. Implement a class named Circle that will have the protected
instance attribute radius - the radius of the circle (readable and modifiable
property). Use the @property decorator.
Then create an instance named circle with radius=3.
In response, display the _dict_ attribute of circle instance.
Expected result:
{'_radius': 3}
73. A class named Circle is given. Add a property called area
(read-only) to the class that calculates the area of a circle with a given
radius. This property should only be computed at first reading or after
modifying the radius attribute. To do this, also modify the way of setting
the value of the
radius attribute in the _init_( ) method. Make sure that the value of the
area attribute is
recalculated after changing the radius attribute.
Then create an instance named circle with radius=3 .
In response, display the value of the area attribute to the console (round
the result to four decimal places).
Expected result:
28.2743
import math
class Circle:
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
self._radius = value
Solution:
74. A class named Circle is given. Add a property called area (read-only) to the
class that calculates the area of a circle with a given radius. This property
should only be computed at first reading or after modifying the radius attribute.
To do this, also modify the way of setting the value of the
radius attribute in the _init_( ) method. Make sure that the value of the area
attribute is
recalculated after changing the radius attribute.
Then create an instance named circle with radius=3 .
In response, display the value of the perimeter attribute to the console (round
the result to four decimal places).
Expected result:
18.8496
import math
class Circle:
def __init__(self, radius):
self.radius = radius
self._area = None
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
self._radius = value
self._area = None
@property
def area(self):
if self._area is None:
self._area = math.pi * self._radius * self._radius
return self._area
75. Implement a class named Rectangle which will have the following
properties:
• width
• height
The width and height of the rectangle, respectively (for reading and for
modification). Also add a property named area that stores the area of the
rectangle (read-only). This property should be computed only at the first
reading or after modifying any of the rectangle sides. Skip attribute
validation.
Then create an instance named rectangle with a width = 3 and a height =
4 and print the information about the rectangle instance to the console as
shown below.
Expected result:
width: 3, height: 4 -> area: 12
ABOUT THE AUTHOR
Edcredibly App –
https://play.google.com/store/apps/details?
id=com.edcredibly.courses