# Exercise: object oriented

### 1. Create an Auto class, including the number of tires, car color, body weight, speed and other attributes, and create instances through different construction methods. At least the car should be able to accelerate and slow down Another car class, CarAuto, inherits Auto, adds air conditioning and CD attributes, and re implements methods to cover acceleration and deceleration

```class Auto:
def __init__(self, tyre=4, color='white', weight=2, speed=0):
self.tyre = tyre
self.color = color
self.weight = weight
self.speed = speed

self.speed += 2
if self.speed >= 180:
self.speed = 180

def sub_speed(self):
self.speed -= 2
if self.speed < 0:
self.speed = 0

def stop(self):
self.speed = 0

class AirConditioner:
def __init__(self, breed='GREE', power=1, type='Cold and warm'):
self.breed = breed
self.power = power
self.type = type

class CD:
def __init__(self, breed='SONY', color='black', price=1000):
self.breed = breed
self.color = color
self.price = price

class CarAuto(Auto):
def __init__(self, tyre=4, color='white', weight=2, speed=0):
super().__init__(tyre, color, weight, speed)
self.air_conditioner = AirConditioner()
self.cd = CD()

self.speed += 4
if self.speed >= 240:
self.speed = 240

def sub_speed(self):
self.speed -= 4
if self.speed <= 0:
self.speed = 0```

### 2. Create a Person class and add a class field to count the number of objects of Perosn class

class Person:
count = 0

```def __init__(self):
if self.__class__ == Person:
Person.count += 1```

class Student(Person):
pass

stu = Student()
print(Person.count)
p1 = Person()
p2 = Person()
print(Person.count)
```

### 3. Create an animal class with attributes: gender, age, color and type (when printing objects of this class, it is required to print them in the form of '/ XXX's object: gender -? Age -? Color -? Type -? /')

```class Animal:
def __init__(self, gender='female', color='black', age=2, type='Crawl'):
self.gender = gender
self.color = color
self.age = age
self.type = type

def __repr__(self):
return '/{}Object: Gender-{} Age-{} colour-{} type-{}/'.format(self.__class__.__name__, self.gender, self.age, self.color, self.type)

a1 = Animal()
print(a1)```

### 4. Write a circle class with attribute radius, area and perimeter. When it is required to obtain the area and perimeter, the corresponding value can be obtained according to the radius value. However, when assigning the area and perimeter values, the program crashes directly, and prompts that the property cannot be assigned

```class ReadOnlyError(Exception):
def __str__(self):
return 'This property cannot be assigned'

class Circle:
pi = 3.1415926

self._area = 0
self._perimeter = 0

@property
def area(self):

@property
def perimeter(self):
return 2 * Circle.pi * self.radius

@perimeter.setter
def perimeter(self, value):

@area.setter
def area(self, value):

c1 = Circle(10)
print(c1.area, c1.perimeter)```

### 5. Write a poker game class, which requires to have the function of licensing and shuffling (specific attributes and other functions can be played according to the actual situation)

```class PokerNum(Enum):
Three = (3, '3')
Four = (4, '4')
Five = (5, '5')
Six = (6, '6')
Seven = (7, '7')
Eight = (8, '8')
Nine = (9, '9')
Ten = (10, '10')
J = (11, 'J')
Q = (12, 'Q')
K = (13, 'K')
A = (14, 'A')
Two = (15, '2')
Joker_S = (16, 'Joker')
Joker_B = (17, 'JOKER')

# print(PokerNum.J, PokerNum.J.value)
# # # Get all the data in the current enumeration class
# for item in PokerNum.__members__.items():
#     print(item, type(item[1]))

class Poker:
def __init__(self, color: str, num: PokerNum):
self.color = color  # ♥,♠,♣,♦
self.num = num   # 2-10, J,Q,K,A; Wang, Xiao Wang

def __repr__(self):
return '{}{}'.format(self.color, self.num.value[1])

# Let the Poker object compare sizes (>
# p1 > p2  ->  p1.__gt__(p2)
def __gt__(self, other):
return self.num.value[0] > other.num.value[0]

class PokerGame:
def __init__(self):
# A deck of cards
self.pokers = []
# Create brand
nums = PokerNum.__members__.items()
colors = ['♥', '♠', '♣', '♦']
for num in nums:
print('>>>')
print(num)
print(num[1])
if num[1] == PokerNum.Joker_S or num[1] == PokerNum.Joker_B:
continue
for color in colors:
# Create a card object
p = Poker(color, num[1])
self.pokers.append(p)

self.pokers.append(Poker('', PokerNum.Joker_S))
self.pokers.append(Poker('', PokerNum.Joker_B))
# print(self.pokers)

def __shuffle(self):
# Method 1: convert to set
# print(set(self.pokers))
# Method 2: random.shuffle (list)
shuffle(self.pokers)
print(self.pokers)

def deal(self):
self.__shuffle()
poker_iter = iter(self.pokers)
p1 = []
p2 = []
p3 = []
for _ in range(17):
p1.append(next(poker_iter))
p2.append(next(poker_iter))
p3.append(next(poker_iter))

# sort
# p1.sort(key=lambda item: item.num.value[0], reverse=True)
# p2.sort(key=lambda item: item.num.value[0], reverse=True)
# p3.sort(key=lambda item: item.num.value[0], reverse=True)
p1.sort(reverse=True)
p2.sort(reverse=True)
p3.sort(reverse=True)

return p1, p2, p3, list(poker_iter)

game = PokerGame()
# game.shuffle()
print(game.deal())

print(game.deal())```

### 6. (try) write a class whose function is: 1. Analyze the content of the specified lyrics file 2. Display the lyrics prompt by time: the content of the lyrics file is generally stored in the following format. The front of the lyrics corresponds to the time, and the corresponding lyrics can be displayed at the corresponding time point

```class Lyric:
def __init__(self):
self._time = 0
self.word = ''

@property
def time(self):
return self._time

@time.setter
def time(self, value):
fen = float(value[1:3])
miao = float(value[4:])
self._time = fen*60 + miao

def __repr__(self):
return '{}:{}'.format(self.time, self.word)

def __lt__(self, other):
return self.time < other.time

class LyricAnalysis:

def __init__(self, song_name: str):
self.__song_name = song_name
self.__lyrics = []

def __analysis_file(self):
# 1. Read the contents of the lyrics file
with open('files/'+self.__song_name+'.lrc', 'r', encoding='utf-8') as f:  # Lyrics files should be added by yourself
while True:
if not line_content:
break

# Separate time from words
lines = line_content.split(']')
word = lines[-1]
for time in lines[:-1]:
lyric = Lyric()
lyric.time = time
lyric.word = word
self.__lyrics.append(lyric)

# Sort lyrics
self.__lyrics.sort(reverse=True)
# print(self.__lyrics)
print('Analysis of lyrics')

def get_lyric(self, time):
"""Get lyrics according to time"""
if not self.__lyrics:
self.__analysis_file()

# Find the first Lyric object less than the specified time
for lyric in self.__lyrics:
if lyric.time <= time:
return lyric.word

l1 = LyricAnalysis('Blue Lotus')
# l1.analysis_file()
print(l1.get_lyric(100))
print(l1.get_lyric(120))```

Keywords: Python Lambda Attribute encoding less

Added by catnip_uk on Thu, 28 Nov 2019 14:53:11 +0200