class Rectangle

Run Settings
LanguagePython
Language Version
Run Command
class Rectangle: color = 'red' def __init__(self, width, height): self.width = width #self is the object which is to be filled in later outside the class, like r1, r2. self.height = height #there is 2 empty columns named as width, and height. def area(self): return self.width * self.height def perimeter(reference_object): #reference_object here is like "self" in area's self. self can be named as anything you want return 2 *(reference_object.width + reference_object.height) # def to_string(self): # return "Rectangle (width={0}, height={1})".format(self.width, self.height) def __str__(self): # write a __str__ to replace the __str__ inside python return "Rectangle (width={0}, height={1})".format(self.width, self.height) def __repr__(self): # write a __str__ to replace the __str__ inside python return "Rectangle({0}, {1})".format(self.width, self.height) def __eq__(self, other): #function to compare width and height, equal print('self ={0}, other ={1}'.format(self, other)) if isinstance(other, Rectangle): return (self.width, self.height) == (other.width, other.height) else: return False def __lt__(self, other): #function to check less than to overwrite the internal function __lt__ if isinstance(other, Rectangle): #check other is an instance of Rectangle return (self.area() < other.area()) else: return NotImplemented #not the same as False, false has some meaning of comparision. #NotImplemented compute the value of "none" something like that #here, by using NotImplemented, if the result of r1 < r2 is false, the other side by ">" will be computed again to check if r2 > r1. r1 = Rectangle(10, 20) #width = 10, height = 20 for r1. or say, r1.width = 10, r1.height = 20. r1 is an object of Rectangle r2 = Rectangle(10, 20) #width = 3, height = 5 for r2. or say r2.width = 3, r2.height = 5. r2 is an object of Rectangle print(r1 is r2) #state the address of r1 is the same of r2, false in this case print(r1 == r2) #state the value of r1 is the same of r2, 10=10, 20=20, true in this case print(r1 == 100) #state the type of r1 is the same of 100, false is this case print(r1.width) print(r1.color, r2.color) print(r1.area()) print(r1 < r2) print(str(r1)) #result shows: <__main__.Rectangel object at 0x7ba42a620c10>, it is an address. main is taken from #the file name:mmain.py. but when __str__ is redefined in line15, str follows line15 and run the function here #print(r1.to_string()) #__xx__ is an internal function #__str__ is the string representation of the object. Here the object is r1. print(Rectangle.__str__(r1)) # def __str__(self): # write a __str__ to replace the __str__ inside python print(r1.__repr__) #show the results <bound method Rectangle.__repr__ of Rectangel (10, 20)> print(dir(r1))
Editor Settings
Theme
Key bindings
Full width
Lines