Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #class to create shape instances, print details, write output to binary file, read output from binary file
- import pickle
- class Shape:
- def __init__(self, x, y, name):
- self.x = x
- self.y = y
- self.name = name
- def area(self): #calculate area of new shape
- return self.x * self.y
- def perimeter(self): #calculate perimeter of new shape
- return 2 * self.x + 2 * self.y
- def scaleSize(self, scale): #function to scale new shape
- self.x = self.x * scale
- self.y = self.y * scale
- def printname(self): #prints name of a shape
- return self.name
- with open('shapes.dat', 'wb') as output: #opens binary file for writing to
- rectangle = Shape(100,45,'rectangle')
- pickle.dump(rectangle, output, pickle.HIGHEST_PROTOCOL) #dumps the output to the file
- square = Shape(55,15,'square')
- pickle.dump(square, output, pickle.HIGHEST_PROTOCOL) #dumps the output to the file
- with open('shapes.dat', 'rb') as input: #opens the binary file in read mode and prints requested content
- rectangle = pickle.load(input)
- print(rectangle.name)
- print(rectangle.x)
- print(rectangle.y)
- square = pickle.load(input)
- print(square.name)
- print(square.x)
- print(square.y)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement