Python object-oriented

Source: Internet
Author: User

Python object-oriented

Python object-oriented classes and attributes

Today, I got started with object-oriented, and found that object-oriented is a world of difference. When I was learning Linux, everything was a file, and now I learned object-oriented, so, everything was an object.

I didn't always learn how to use function-oriented programming. I can do everything with functions, but why should I use object-oriented programming? Object-oriented greatly improves the scalability of the program. In the face of constant changes in demand, the superiority of object-oriented is presented, and the process of transition from function-oriented to object-oriented is excessive.

Here is an example:

# Def dog (name, gender, type): # dog Action # def jiao (dog): # print ('one dog [% s], wang Wangwang '% dog ['name']) # it can be the same as the function name dog or the dictionary return value do (preferably the same as the return value) # def chi_fan (dog): # print ('one [% s] is eating '% dog ['type']) # dog = {# 'name': name, # 'gender': gender, # 'type': type, # 'jiao': jiao, # 'chi _ Shi': chi_fan, #}# return dog # d1 = dog ')
Output result:
# {'Name': 'awesome ', 'Gender': 'male', 'type': 'Chinese dog', 'jiao': <function dog. <locals>. jiao at 0x005912B8>, 'chi _ fan ': <function dog. <locals>. chi_shi at 0x00591270>}
 

From the preceding example, we can see that a dog function is defined. In this function, the jiao and chi_fan functions are defined, and a dictionary is defined, in this dictionary, we define the data attributes of dog, such as name and gender, as well as the function attribute "and" eat ". At the end of the function, a returned return value" dog "is returned, print the value of d1 and you will find that a dictionary type data is obtained. The function attribute returns the memory address of the function.

Improvements on this basis:

Def dog (name, gender, type): # dog Action # def jiao (dog): # print ('one dog [% s], wang Wangwang '% dog ['name']) # def chi_fan (dog): # print ('one [% s] is eating' % dog ['type']) # def init (name, gender, type): # Dog attributes and dog methods (the return value is also used as a method) # dog1 = {# 'name': name, # 'gender': gender, # 'type': type, # 'jiao': jiao, # 'chi _ Shi': chi_fan, #}# return dog1 # return init (name, gender, type) # (pass the function name as a parameter) # d1 = dog ('awesome ', 'male ', 'chinance') # print (d1) # d1 ['jiao'] (d1) # The jiao function needs to input a parameter. The parameter is the result output of the Dog "d1: A dog [awesome], Wang Wangwang

This time, the returned value is made into an init function based on the previous one. This function is used to execute the content in the dictionary. To call a method defined in def dog, the call method is as follows: d1 ['jiao'] (d1) # Call the dictionary value and enclose the brackets to run this function.

Whether or not the function-oriented implementation encapsulates dog attributes and methods in the function for implementation. Well, we will use object-oriented implementation to implement the above functions:

Class Dog: def _ init _ (self, name, gender, type): self. name = name self. gender = gender self. type = type def jaio (self,): print (a dog named % s is calling '% (self. name) def chi_fan (self,): print ('a dog named % s is eating at dinner '% (self. name) d1 = Dog ('awesome ', 'male', 'male') print (d1) # <__ main __. dog object at 0x004D6690> print (d1. _ dict _) # {'name': 'awesome ', 'Gender': 'male', 'type ': 'male'} d1.chi _ fan () # a dog named awesome is eating

To sum up, class: integrates the same features and actions of a class of things, and class is an abstract concept. Object: a specific thing (exists) created based on the class, and the action and feature are combined.

Next, let's take a look at the data attributes and function attributes of the class:

Class Chinese: 'Chinese class' ren = 'China' def watch_ TV (self): print ('awesome stream') def cha_dui (self ): print ('inserted to the frontend') print (Chinese. ren) Chinese. watch_ TV ('kjk ') Chinese. cha_dui ('') # print (dir (Chinese) # view the existing method print (Chinese. _ dict _) # view the attribute dictionary print (Chinese. _ dict _ ['ren']) Chinese. _ dict _ ['Watch _ TV '] (1) Chinese. _ dict _ ['cha _ dui'] (1) # The output result is: The Chinese drama is inserted in front of ['_ class __', '_ delattr _', '_ dict _', '_ dir _', '_ doc _', '_ eq __', '_ format _', '_ ge _', '_ getattribute _', '_ gt _', '_ hash __', '_ init _', '_ init_subclass _', '_ le _', '_ lt _', '_ module __', '_ ne _', '_ new _', '_ reduce _', '_ performance_ex _', '_ repr __', '_ setattr _', '_ sizeof _', '_ str _', '_ subclasshook _', '_ weakref __', 'cha _ dui', 'ren', 'Watch _ TV '] {' _ module _ ':' _ main __', '_ doc _': 'Chinese class', 'ren': 'China', 'Watch _ TV ': <function Chinese. watch_ TV at 0x008425b8>, 'cha _ dui': <function Chinese. cha_dui at 0x00811270>, '_ dict _': <attribute '_ dict _' of 'China' objects>, '_ weakref __': <attribute '_ weakref _' of 'China' objects>} The Chinese drama has been pushed to the forefront.

Add, delete, modify, and query class attributes:

Class Chinese: country = 'China' def _ init _ (self, name): self. name = name def play_ball (self, ball): print ('% s is hitting % s' % (self. name) # view print (Chinese. country) ### modify Chinese. country = 'Japan 'print (Chinese. country) # p1 = Chinese ('Alex ') print (p1. _ dict _) # The returned Dictionary data attribute print (p1.country) stored in init of p1 object) # First, find the value in the data attribute of p1. If the value does not exist, find it in the Data Attribute of the class ### add Chinese. ren = 'China' # print (Chinese. ren) print (p1.ren) # first, find the value in the data attribute of p1. If the value does not exist, find it in the Data Attribute of the class. # Delete del Chinese. rendel Chinese. country # print (Chinese. _ dict _) # print (Chinese. country) # AttributeError: type object 'China' has no attribute 'country' # Add method def eat_food (self, food ): print ('% s eating % s' % (self. name, food) # Chinese. eat = eat_food # {'_ module _': '_ main _', '_ init _': <function Chinese. _ init _ at 0x021E1300>, 'play _ ball': <function Chinese. play_ball at 0x021E12B8>, '_ dict _': <attribute '_ dict _' of 'China' objects>, '_ weakref __': <attribute '_ weakref _' of 'China' objects>, '_ doc _': None, 'eat ': <function eat_food at 0x021E1348 >}# print (Chinese. _ dict _) p1.eat ('Rice ') # alex is eating #

Add, delete, modify, and query instance attributes:

Class Chinese: country = 'China' def _ init _ (self, name): self. name = name def play_ball (self, ball): print ('% s is hitting % s' % (self. name, ball) p1 = Chinese ('awesome ') # instantiate an object p1print (p1. _ dict __) # print all attributes in p1 (only numeric attributes exist in the instantiated object) # view print (p1.name) print (p1.play _ ball) # bound method Chinese. play_ball of <__ main __. chinese object at 0x00426690 >## add p1.age = 18 print (p1. _ dict _) print (p1.age) #### modify p1.age = 19 print (p1. _ dict _) print (p1.age) ### Delete del p1.ageprint (p1. _ dict __)

Example of retrieving class attributes and instantiating attributes:

Class Chinese: country = 'China' l = ['A', 'B'] def _ init _ (self, name): self. name = name def play_ball (self, ball): print ('% s is hitting % s' % (self. name, ball) p1 = Chinese ('SB ') print (p1.l) # Find it in init of p1, if not, the data attribute p1.l = [, 3] # Of the class will be searched for in class Chinese. It is to add a data attribute 'l' to the instantiated object p1: [1, 2, 3] print (Chinese. l) # ['A', 'B'] print (p1. _ dict _) # {'name': 'SB ', 'L': [1, 2, 3]} p1.l. append ('C') print (p1. _ dict _) # {'name': 'SB ', 'L': [1, 2, 3 ,' C ']} print (Chinese. l) # ['A', 'B'] country = 'China' ----------------- 'class Chinese: country = 'China' def _ init _ (self, name): self. name = name print ('--->', country) def play_ball (self, ball): print ('% s Hitting % s' % (self. name, ball) # print (Chinese. _ dict _) # {'_ module _': '_ main _', 'country': 'China', '_ init __': <function Chinese. _ init _ at 0x006E1300>, 'play _ ball': <function Chinese. play_ball at 0x006E12B8> ,'_ _ Dict _ ': <attribute' _ dict _ 'of 'China' objects>,' _ weakref __': <attribute '_ weakref _' of 'China' objects>, '_ doc _': None} # print (Chinese. country) # China p1 = Chinese ('SB ') # ---> China ----------------- print ('instance -------- "', p1.country) # instance -------- China # Note: Click (.) when you access a variable, you can search for the variable in the class. Generally, the variable is not accessed by instantiating an object or class name point. Then, you can search for the variable outside the class.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.