Create a dog, the dog is the object, he has two aspects
1. Characteristics of dogs: names, genders, etc.
dog1 = { ' name ' : ' wangcai ' , ' gender ' : ' male ' , ' type_ ' : ' Tibetan Mastiff ' , }
2. Dog's ability: can sit, run, bark, bite, etc.-a function can be used to express a capability
def sit (dog1): print ( 'A dog {% s}, sit on the ground ' % dog1 [ ' name ' ]) def run (dog1): print ( 'A dog {% s} is running ' % dog1 [ ' type_ ' ])
The characteristics and functions of dogs are separated, how to make a connection between them? -One way is to add to the dictionary
dog1 = { 'name': name, 'gender': gender, 'type_': type_, 'sit':sit, 'run': run }
In this way, the characteristics and functions of a dog are unified in a dictionary.
# Dog features DEF SIT (DOG1): Print ( ' dog {% s}, sitting on the ground ' % DOG1 [ ' name ' ]) def run (dog1): print ( 'A dog {% s} is running ' % dog1 [ ' type_ ' ]) # 狗 的 CHARACTER dog1 = { ' name ' : name, ' gender ' : gender, ' type_ ' : type_, ' sit ' : sit, ' run ' : run }
Finally, a function can be used to wrap this function and feature to avoid being called casually
DEF Dog (): # Dog function DEF SIT (DOG1): Print ( ' dog {% s}, sitting on the ground ' % DOG1 [ ' name ' ]) def run (dog1): print ( 'A dog {% s} is running ' % dog1 [ ' type_ ' ]) # 狗 的 CHARACTER dog1 = { ' name ' : name, ' gender ' : gender, ' type_ ' : type_, ' sit ' : sit, ' run ' : run } return dog1
Call the features and functions inside, still need to return to us through return
To further improve, functionalize the dictionary content
DEF Dog (): # Dog function DEF SIT (DOG1): Print ( ' dog {% s}, sitting on the ground ' % DOG1 [ ' name ' ]) def run (dog1): print ( 'A dog {% s} is running ' % dog1 [ ' type_ ' ]) # Features of dog def init (name, gender, type_) dog1 = { 'name': name, 'gender': gender, 'type_': type_, 'sit': sit, 'run':run } return dog1 return init(name,gender,type_)
An entire object-oriented programming is completed
DEF () Dog: # feature dog def init(name,gender,type_) dog1 = { 'name': name, 'gender': gender, 'type_': type_, 'sit': sit, 'run': run } return dog1 # Dog features DEF SIT (DOG1): Print ( ' dog {% s}, sitting on the ground ' % DOG1 [ ' name ' ]) def run (dog1): print ( 'A dog {% s} is running ' % dog1 [ ' type_ ' ]) return init(name,gender,type_)
Then you can call
d1 = dog ( ' Wangcai ' , ' Mother ' , ' Tibetan Mastiff ' ) d2 = dog ( ' dog dog ' , ' mother ' , ' hunter ' ) D1 [ ' a ' ] (d1) d2['run'](d2)
An entire object-oriented programming is completed
Does it look like classes and objects?
class Dog(): def __init__(self, name, gender): self.name = name self.gender = gender def sit (self): print ( 'A dog% s, sit on the ground ' % self.name) def run (self): print ( 'A dog {% s} is running ' % self.gender)