I. Interaction between objects
Now that we have a human being, we can go to a real person through some specific attributes of the human being.
Now we're going to create a dog class, and the dog can't beat people. Can only bite people, so we give the dog a bite method.
With dogs, we also have to instantiate a real dog out.
Then the man and the dog can fight. Now let's get them to fight!
Creating a Dog Class
Class Person: role = ' person ' #静态属性 def __init__ (self,name,sex,hp,ad): self.name = name self.sex = Sex self.hp = hp self.ad = AD def attack (self): print ('%s launched an attack '%self.name) class Dog: role = ' Person ' #静态属性 def __init__ (Self,name, kind, HP, AD): self.name = name Self.kind = Kind self.hp = hp
self.ad = AD def bite (self): print ('%s bit a bite '%self.name) Alex = person (' A_alex ', ' ominous ', 1,5) Boos_jin = Person (' King boss ', ' female ', 20,50) Teddy = Dog (' Dumb ', ' Teddy ', 50,10) alex.attack () #相当于执行Person. Attack (Alex) Boos_ Jin.attack () #相当于执行Person. Attack (Boss_jin) Teddy.bite ()
Execution output:
A_SB launched an attack.
Kim's boss launched an attack.
A fool bites a man in a mouthful
Then the question came, and the man launched an attack, who did he attack?
Interactive Teddy hit Alex for a second.
Class Person: role = ' person ' # static attribute def __init__ (self, name, sex, HP, AD): self.name = name # object Property Property self.sex = sex self.hp = hp self.ad = AD def attack (self): print ('%s launched an attack '% Self.name) class Dog: role = ' person ' # static property def __init__ (self, name, kind, HP, AD): self.name = name # object Property Property s Elf.kind = Kind self.hp = hp self.ad = AD def bite (Self, people): # People is a variable name, it is an object PEOPLE.HP-= self.ad # people drop the Blood print ('%s bit%s A mouthful,%s lost '%s '% (Self.name, People.name, People.name, Self.ad) # because people is an object, take name is People.namealex = person (' a_sb ', ' unknown ', 1, 5) Boss_jin = person (' King boss ', ' female ', ', ') Teddy = Dog (' dumb ', ' t Eddy ', Teddy.bite (Alex) # Alex is an object that passes the object in print (ALEX.HP) # view Alex's Blood
Python Full stack learning--day18 (object-oriented interaction)