Python-object-oriented (a basic concept)

Source: Internet
Author: User

I. Python introduction Python is a portable object-oriented scripting language. Although Python is a scripting language, it is also a fully object-oriented language. Since the ease of use was designed as a very important consideration, it is very simple and elegant to use (the syntax is very flexible), so Python can be used to quickly compile and write executable code. Compared with C/C ++, Python programs run slowly. Since a language can survive, it has its own reasons. The same is true for Python. Today's computer processing speed is very fast. For some tasks, running speed is not the primary consideration. For example, to automate database access, a code generator for database access is required. This is a common task. It involves many programming aspects, including string processing and database access, it may also include a GUI system. This task is obviously not suitable for writing in C or C ++, because C/C ++ can save a little running time, But it wastes a lot of development time. Therefore, there are no good or bad languages. C ++ is a static strong type language, while Python is a dynamic strong type language. Because it is a dynamic language, the type of the variable is not explicitly specified by the keyword, but dynamically determined at runtime based on the value assigned to it. In addition, Python supports both structured programming and object-oriented programming, just like C ++. Python is summarized as follows: 1. Python is object-oriented. It supports inheritance, multi-inheritance, polymorphism, Operator overloading, and other object-oriented concepts. 2. Python is portable. Programs Written in Python can run on multiple platforms without modification. This is similar to Java. However, Python also provides some Plantform dependent modules. Be careful when using these modules because they cannot be transplanted. 3. Python is an explanatory language. To be accurate, Python first compiles the source program into intermediate code (similar to java and c #), and then explains and executes the code. Note that the compilation process is transparent to programmers (which is different from java and c #). 4. Python is a dynamic language. It supports metadata programming and advanced features of modern languages such as runtime compilation and execution. These are hard to implement or even cannot be implemented in C/C ++. Python even allows you to add a member of an object during running! 5. Everything is an object! Objects in Python are much more conceptual than other languages. For example, a class is an object, so you can use it during running, unlike C ++, class is the object during compilation. This makes Python highly dynamic. 6. Automatic Memory Management. Like java, you do not need to manage the memory used by your code. In C and C ++, it was a nightmare. 7. Others: Python can use components written in c/c ++, or embed python code into c/c ++ code for execution. Class 2 Definition
First, let's look at the example below.
Class ZZClass:
ClassNum = 0
Def _ init _ (self ):
Self. num = 1
ZZClass. classNum + = 1
Print ("ZZClass _ init _ called .")


Def _ del _ (self ):
ZZClass. classNum-= 1;
Print ("ZZClass _ del _ called .")

Def Hello (self ):
Print ("hello world! ")
Self. PrintClassNum (10) # You can call static functions in common functions.


Def setNum (self, num ):
Self. num = num

Def getNum (self ):
Return self. num

@ Staticmethod
Def PrintClassNum (num = 100 ):
Print (ZZClass. classNum) # In a static method, you can only use the class name callback class variable
# Print classNum # You cannot directly invoke class variables in static methods.
# Print self. num # instance variables cannot be accessed in static methods
Print num


@ Classmethod
Def ClassMethod (cls ):
# Print cls. num # instance variables cannot be directly accessed in class methods
Print "class method ."
Print cls. classNum # You can directly invoke class variables in class methods.


MyObj = ZZClass ()
MyObj. Hello ()
ZZClass. PrintClassNum (10) # You can use a class name to access static methods.
MyObj02 = ZZClass ()
MyObj02.PrintClassNum () # You can access static methods through object instances.
Print myObj. classNum # You can use an object instance to sort class variables.
Print ZZClass. classNum # You can use the class name to access static variables.




MyObj. setNum (10)
MyObj02.setNum (20)
Print myObj. getNum ()
Print myObj02.getNum ()

MyObj02 = 0
Print ZZClass. PrintClassNum ()

Print ZZClass. ClassMethod () # Call the class method through the class
Print myObj. ClassMethod () # Call a class method through an instance



Output result:
ZZClass _ init _ called. hello world! 110110 ZZClass _ init _ called.2100221020ZZClass _ del _ called.1100Noneclass method.1NoneZZClass _ del _ called.


Analysis: 1. compared with C ++, methods defined in Python use the def keyword. The methods defined in the class have at least one parameter, generally, the variable named 'self 'is used as this parameter (other names can also be used), and must be used as the first parameter to reference the variable of the object. Similar to c ++'s this pointer, this pointer is hidden in C ++ and is handled by the compiler. 2. Use "." instead of "->" to access function calls and variables. 3. _ init _ is similar to a constructor. It is called when an object is generated. It can be used for initialization operations and is called without display. The system will execute it by default. The constructor supports overloading. If you have not redefined the constructor, the system automatically runs the default constructor. _ Del _ is similar to a destructor. This API is called when an object is released. It supports reload. You can release resources without displaying the call. 4. instance variables and class variables: num is an instance variable, and classNum is a class variable. The former is similar to the member variables of C ++, and the latter is similar to the static variables of C ++ classes. Class variables are shared by all objects and can be accessed directly using "class name. variable name" without an object. Like C ++, you can also use class variables when using an object instance. An instance variable is a copy of each object and can only be accessed through the object. The instance variables do not need to be displayed and defined in the class. Note: class variables can be accessed through class names and instance objects. You can modify class variables by class names. The data shared by this class and all instances will be modified, accessing the data through a class or instance again will produce new data, which is consistent with that of C ++. However, when you modify a class variable through an instance object, the effect will only be applied to the instance. The old data is still obtained when you access the instance through the class or other instances again. However, this modification method will instantiate this type of variable. The result is that the instance will get a separate copy of this variable, and this object will no longer share the variable with the class. (Python is a bit complicated.) Let's look at the following example:
Class classA:
ClassVar =''
Def _ init _ (self ):
Pass

Def set_var1 (self, x ):
ClassA. classVar = x

Def set_var2 (self, y ):
Self. var2 = y
Return self. var2


Oa = classA ()
Ob = classA ()


Oa. set_var1 ("class variable .")
Print oa. classVar # class variable.
Print ob. classVar # class variable.

Oa. classVar = "changed ."
Print oa. classVar # changed.
Print ob. classVar # class variable.

Oa. set_var1 ("class variable01 ")
Print oa. classVar # changed.
Print ob. classVar # class variable01


Ob. set_var1 ("class variable02 ")
Print oa. classVar # changed.
Print ob. classVar # class variable02

Ob. set_var2 ("inst variable ")
Print ob. var2
# Print oa. var2 # error! Because var2 is a instance variable

If you want to modify the class attributes outside the class, you must reference them through the class object and then modify them. If an instance object is referenced, an instance attribute with the same name is generated. In this way, the instance attribute is modified without affecting the class attribute, in addition, if you reference the attributes of this name through an instance object, the instance property will be forcibly blocked, that is, the instance property is referenced, unless this instance property is deleted.
5. common functions and static functions: Hello is a common function, and PrintClassNum is a static function. PrintClassCount () is similar to a C ++ static function. Just as a static function does not have the this pointer, it does not have the self variable. Static functions can only access static member variables (class variables ). Like C ++, you can use instance objects and class names to call static functions. You can only use instance variables to call common functions. Common functions (Instance functions) outside the class can only be called through instance objects, but cannot be called in other ways.
6. Class Functions and static functions: ClassMethod is a class method with a parameter (Class Object ). Similar to static methods, they can all be called through classes and instances, and cannot access instance members. Class methods can be accessed through their own cls internal class members, but static methods do not. They can be accessed indirectly through class names. Staticmethod does not require parameters. classmethod requires class variables to be passed as parameters (rather than class instances). A class function can also be used to modify class attributes.
7. variable access attributes: the object-oriented Syntax of C ++ is relatively standard and has public, private, and protected data types, while the python class has no permission control, all variables can be called externally. Although we can add a Double Slide __in front of variables or methods, this indicates private access permission. In fact, it is implemented internally, is to convert private variables, the rule is: _ <class name >__ <private variable>. However, this is actually a pseudo-private mechanism of python. It is just a programmer's Convention. A Double underline is added to indicate a private variable, but it can still be called if it is to be called externally. See the following example:
Class Test:
Count = 0
Def _ init _ (self, c ):
Self. count = c
Self. _ name = "zhangzhe" # private variable
Self. _ class _. count = self. _ class _. count + 1

Def _ get_name (self): # private Method
Return self. _ name

Def get_counte (self ):
Return self. count


A = Test (3)
Print a. count #3
# Print a. name # AttributeError: Test instance has no attribute 'name'
Print Test. count #1
Print a. get_counte () #3

Print a. _ dict _ # {'Count': 3, '_ Test _ name': 'hangzhou '}
Print a. _ Test _ name # zhangzhe

Print Test. _ dict _ # {'Count': 1, '_ module _': 'classdemo02 ',' _ Test _ get_name ': <function _ get_name at 0x101e92500>, '_ doc _': None, '_ init _': <function _ init _ at 0x101e92488>, 'Get _ counte': <function get_counte at 0x101e92578>}
Print a. _ Test _ get_name () # zhangzhe


B = Test (-1)
Print B. count #1
Print Test. count #2

The _ name defined here is a private property, __get_name () is a private method. If you directly access it, you will be prompted to not find the relevant property or method. You can use a. _ Test _ name and a. _ Test _ get_name () to access private variables and methods.
Note:In Python, keywords such as public and private in C ++ are not used to distinguish between public and private attributes. They are distinguished by attribute naming, if two underscores '_' are added before the property name, it indicates that the property is a private property; otherwise, it is a public property.
Summary: For class attributes and instance attributes, if a certain attribute is referenced in the class method, this attribute must be a class attribute. If an attribute is referenced in the instance method (not modified ), A class property with the same name exists. If the instance object has an instance property with the same name, the instance property will block the class property, that is, the instance property is referenced, if the instance object does not have an instance attribute of this name, the class attribute is referenced. If an attribute is changed in the instance method and a class attribute with the same name exists, in this case, if an instance object has an instance attribute with this name, the instance attribute is modified. If the instance object does not have an instance attribute with this name, an instance attribute with the same name is created. If you want to modify the class attributes, you can modify them through the class object. If you want to modify the class attributes, you can only modify them in the class method.
It can be seen from the definition form of class methods, instance methods, and static methods. The first parameter of class methods is the class Object cls, cls references the attributes and methods of class objects. The first parameter of the instance method is the Instance Object self, the reference through self may be a class attribute or an instance attribute (which needs to be analyzed). However, if there are class attributes and instance attributes with the same name, the instance has a higher priority. No additional parameter is required for static methods. Therefore, if a class attribute is referenced in a static method, it must be referenced through a class object.

From the above point of view, Python is very flexible, and its object orientation is not truly inaccessible. It is just an agreement for everyone to follow, just as we all use self to represent the current object in the class, you can also use others, but everyone is used to self.

Built-in methods in the three categories
In addition to the init and del methods above, the Python class also has the following built-in methods (similar to Operator Overloading in C ++ ):

1. _ new _ () :__ new _ () is called before _ init _ () to generate instance objects. This method and class attributes can be used to implement the singleton mode in the design mode. Is Singleton mode used to create a unique object? A singleton mode class can only instantiate one object. For example, the following code: _ instance = None def _ new _ (cls, * args, ** kwargs): # if ZZClass is called before the init function. _ instance is None: # produce a unique instance
Print ("ZZClass _ new _ called .")
ZZClass. _ instance = object. _ new _ (cls, * args, ** kwargs)
Return ZZClass. _ instance
2. _ getattr _ (), _ setattr _ (), and _ getattribute _ (): when reading an attribute of an object, python automatically calls the _ getattr _ () method. For example, fruit. color is converted to fruit. _ getattr _ (color ). When the attribute is set using the value assignment statement, python automatically calls the _ setattr _ () method. The function of _ getattribute _ () is similar to that of _ getattr _ (). It is used to obtain the attribute value. However, _ getattribute _ () provides better control and stronger code. Note that the _ setattribute _ () method does not exist in python.
3. _ str _ () indicates the meaning of an object and returns a string. after the _ str _ () method is implemented, you can directly use the print statement to output the object, or use the str () function to trigger the execution of _ str. In this way, the object and the string are associated to facilitate the implementation of some programs. This string can be used to represent a class.
Example: def _ str _ (self): return "ZZClass itself ."
4. _ call _ (): implements the _ call _ () method in the class. You can directly return the content of _ call _ () when creating an object. This method can be used to simulate static methods. Example: class InternalClass:
Def _ call _ (self, * args, ** kwargs ):
Print "internal class ."

Func = InternalClass () # Call InternalClass (). In this case, InternalClass is returned as a function,
# This defines the method func () for the external class ZZClass. func () executes the code in _ call.
MyObj. func () # internal class. myObj. func () # internal class.
5. _ getitem _ (): If a class defines an attribute as a sequence, use _ getitem _ () to output an element in the sequence attribute.
Class Persons:
Def _ getitem _ (self, item ):
Return self. persons [item]

AllPersons = Persons ()
AllPersons. persons = ["Alice", "Joe"]
Print allPersons [1]
Supplement: strong language
A language that always enforces type definition. Java and Python are mandatory Type Definitions. If you have an integer that is not displayed for conversion, you cannot regard it as a string.
Weak Type Definition Language
A language that can be ignored, opposite to a strong type definition. VBScript is defined as a weak type. In VBScript, you can connect the string '12' and integer 3 to get the string '123'. Then, you can regard it as an integer of 123 without display conversion.
Note: The Central Word of the strong/weak type is 'type', not a variable. Whether a variable can be bound to multiple types is irrelevant to whether the language is strong or weak.
In the compilation phase, the dynamic Compilation Program does not know exactly the function to be called. Only when the program is running can it determine the function to be called. Therefore, it is necessary to know exactly the called function, it is required that the compilation work be carried out when the program is running. Such association work is called Dynamic Association work when the program is running. In fact, it is not a feature of Python, and all object-oriented languages basically need to be implemented. It enables the execution of an object method to use its own (or its class) method, rather than its parent class method. The Common Implementation of Dynamic concatenation is to store the function entry address in a table (for example, a c ++ virtual table ), when running, you can use the dynamic table search method to determine which function should be called. Function execution efficiency is not higher than static Association, but it is more flexible.
Static Association editing static Association editing refers to the compilation and connection phase. Such association is also called early Association editing, during compilation, it solves the relationship between the operation calls in the program and the code that executes the operation.

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.