class Animal: def __init__(self, name, age, color, food): self.name = name self.age = age self.color = color self.food = food def run(self): print(f"{self.name}Running") self.get_age() self.eat() def get_age(self): print(f'{self.name}this year{self.age}year') def eat(self): print(f'{self.name}I am eating{self.food}') cat = Animal('Tom', 3, 'black', 'fish') cat.run() # Call other methods through the run method mouse = Animal('Jerry', 2, 'white', 'cheese') mouse.run() # Call other methods through the run method dog = Animal('Wangcai', 4, 'white', 'scrag') dog.run()
Define a car class, define a move method in the class, and then create BMW respectively_ X9,AUDI_A9 object and add attributes such as color, horsepower and model, then print out the attribute value respectively, call the move method, and print 'the car starts running' in the move method (use the _init _methodto complete the attribute assignment)
# Automobile class Car(object): def __init__(self, color, speed, type): self.color = color self.speed = speed self.type = type def move(self, name): print(name + "The car began to run") # BMW_X9 object BMW_X9 = Car("red", 80, "F4") print('BMW_X9 The attributes are:',BMW_X9.color, BMW_X9.speed, BMW_X9.type) BMW_X9.move('BMW_X9') # AUDI_A9 object AUDI_A9 = Car("black", 100, "S3") print('AUDI_A9 The attributes are:',AUDI_A9.color, AUDI_A9.speed, AUDI_A9.type) AUDI_A9.move('AUDI_A9')
Define a human, set the corresponding attributes (name, age, gender) in the init method, Create two objects respectively, using__ str__ Method combines personal information into a string, returns it, and prints it out
class Person: """ Define a human "class" """ def __init__(self, name, weight): self.name = name self.weight = weight def __str__(self): return "My name is%s Weight is%.2fkg" % (self.name, self.weight) xiaoming = Person("Xiao Ming", 56) xiaomei = Person("Xiaomei", 44) print(xiaoming) print(xiaomei)
The school member class has the properties of name and total number of members. Teacher s inherit the class of school members and add additional salary attributes. The Student class inherits the school member class and adds additional performance attributes. Requirements: when creating teacher and student objects, add 1 to the total number, and print relevant names and salary / achievement information; If the object is deleted, the total number of people will be reduced by 1
class SchoolMember: count = 0#Total object counter def __init__(self,name): self.name = name SchoolMember.count += 1#Add 1 to the new object print("The total number of people is", SchoolMember.count) def dell(self, types):#delete object SchoolMember.count -= 1 # Total quantity minus one print(f'reduce{types}Members:{self.name}') del self # Delete current object print("The total number is",SchoolMember.count) class Teacher(SchoolMember): # Teachers, inheriting schools def __init__(self,name,salary): # Initialization method, additional salary attribute added print(f'Add a teacher member. The basic information is: name{name},salary{salary}') SchoolMember.__init__(self,name) # Call the init method of the parent class to add one to the member self.salary = salary class Student(SchoolMember): # Students, inheriting schools def __init__(self,name,score): # Initialization method, additional score attribute added print(f'Add student members. The basic information is: name{name},The result is{score}') SchoolMember.__init__(self, name, ) # Call the init method of the parent class to add one to the member self.score = score print("Add operation") t1 = Teacher("zhangsan", 1000) # Create teacher object t2 = Teacher("lisi", 2000) s1 = Student("wangwu", 90) # Create student object s2 = Student("zhaoliu", 95) print("Delete operation") t1.dell('teacher') # Call the delete method. There is no delete method in the teacher and student classes, but the parent class has. It will inherit the dell method of the parent class. The value is passed to judge whether the deleted member is a teacher or a student, which is just a visual display s1.dell('student')
Create a pancake class and call the method of cooking time to accumulate the pancake status. If the frying time is between 0-3, the status is raw. If the frying time is between 3-5, the status is half cooked. If the frying time is between 5-8, the status is fully cooked. When the time exceeds 8 minutes, the status is burnt, and you can also add ingredients to the pancake, such as green onions and eggs?, Roast sausage, etc
class PanCake: def __init__(self): self.cooking_time = int(input('Please enter cooking time:')) self.Seasoning = input('Please enter the seasoning to be added:') def cook_time(self): if 0 < self.cooking_time <= 3: print(f'You fried a raw one{self.Seasoning}grilled savory crepe') elif 3 < self.cooking_time <= 5: print(f'You fried a half cooked one{self.Seasoning}grilled savory crepe') elif 5 < self.cooking_time <= 8: print(f'You fried one well done{self.Seasoning}grilled savory crepe') elif self.cooking_time > 8: print(f'You fried a burnt one{self.Seasoning}grilled savory crepe') else: print('Your input is incorrect') pancake1 = PanCake() pancake1.cook_time()
Demand: police officers and police dogs work together. Police dogs are divided into two types: chasing the enemy and tracking down drugs. Police officers carry different dogs and perform different tasks. Analysis: there are two categories of police officers and police dogs, which are completed by polymorphism
class Dog(object): def work(self): pass class ArmyDog(Dog): def work(self): print('follow up the enemy') class DrugDog(Dog): def work(self): print('Trace drugs') class People(object): def with_dog(self, dog): dog.work() ad = ArmyDog() dd = DrugDog() zs = People() zs.with_dog(ad)
Soldier XX has a gun (AK47). Soldiers can fire guns and fire bullets. Guns can add bullets Gun type: attribute: model, number of bullets, behavior (method): fire bullets, add bullets Soldier class: attribute: soldier name, gun behavior: firing behavior (need to consider: whether there is a gun? And adding bullets and firing bullets)
class Gun(object): def __init__(self, model): # Set the gun model and the number of bullets self.model = model self.bullet_count = 0 def __str__(self): # Returns the status of the current gun type. The gun type has the remaining bullets return "{}have{}Fire a bullet".format(self.model, self.bullet_count) def shoot(self): # Fire bullets if self.bullet_count > 0: # When the number of bullets is greater than 0, the bullets will be fired and the number of bullets will be reduced by one print("Fire bullets") self.bullet_count -= 1 def add_bullet(self, count): # Add bullets if self.bullet_count == 0: # But the bullet is 0. Add bullets print('There are no bullets. We're adding bullets') self.bullet_count += count print("Add bullets:{}Grains".format(count)) class Soldier(object): # Soldier class def __init__(self, name): self.name = name self.gun = 0 def fire(self): # FireStarter if self.gun == 0: print("{}No guns yet".format(self.name)) else: self.gun.add_bullet(10) print("FireStarter") self.gun.shoot() # Create a gun object AK47 = Gun("AK47") print(AK47) # Create soldier object keen = Soldier("keen") keen.fire() keen.gun = AK47 for i in range(11): keen.fire() print(AK47)