elena1234

Abstract class, getter and setter in Python

Feb 6th, 2022 (edited)
532
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.22 KB | None | 0 0
  1. from abc import ABC, abstractmethod, abstractproperty
  2.  
  3. class Shape(ABC):
  4.     @abstractproperty
  5.     def area(self):
  6.        pass
  7.    
  8.     @area.setter
  9.     def area(self, value):
  10.        pass
  11.        
  12.     @abstractproperty
  13.     def perimeter(self):
  14.        pass
  15.    
  16.     @perimeter.setter
  17.     def area(self, value):
  18.        pass
  19.        
  20.     def print_shape(self):
  21.          print(f"Area is: {self.area} and perimeter is: {self.perimeter}")
  22.          
  23.  
  24. class Rectangle(Shape):
  25.     def __init__(self, area, perimeter):
  26.         self.area = area
  27.         self.perimeter = perimeter
  28.      
  29.     @property  
  30.     def area(self):
  31.         return self.__area
  32.    
  33.     @area.setter
  34.     def area(self, value):
  35.         if value > 0:
  36.             self.__area = value
  37.         else:
  38.             raise ValueError("The area can not be negative!")
  39.        
  40.     @property
  41.     def perimeter(self):
  42.         return self.__perimeter
  43.    
  44.     @perimeter.setter
  45.     def perimeter(self, value):
  46.         if value > 0:
  47.             self.__perimeter = value
  48.         else:
  49.             raise ValueError("The perimeter can not be negative!")
  50.                
  51.            
  52. rectangle1 = Rectangle(10, 40)
  53. rectangle1.area = 9
  54. rectangle1.print_shape()
  55.  
Add Comment
Please, Sign In to add comment