Describes attributes, methods, encapsulation, and inheritance instances based on python3. describes python3 instances.

Source: Internet
Author: User

Describes attributes, methods, encapsulation, and inheritance instances based on python3. describes python3 instances.

Python class

Classes in Python provide all the basic functions of object-oriented programming: the class inheritance mechanism allows multiple base classes, and the derived classes can override any methods in the base class, you can call methods of the same name in the base class.

Objects can contain any number of data types.

Similar to c ++, python classes provide class encapsulation, inheritance, multi-inheritance, constructor, and destructor.

In python3, the top-level parent class of all classes is an object class. Similar to java, if the parent class is not written during class definition, the object class is its direct parent class.

Class Definition

The syntax format of the class definition is as follows:

class ClassName:<statement-1>...<statement-N>

Class Object: after creating a class, you can access and change its attributes and methods by class name.

Instance Object: after the class is instantiated, you can use its attributes to dynamically add attributes (similar to javascript) to the instance object without affecting the class object.

Class attributes

You can use vertex (.) to access object attributes.

You can also use the following functions to access attributes:

Getattr (obj, name [, default]): Access Object Attributes

Hasattr (obj, name): Check whether an attribute exists.

Setattr (obj, name, value): sets an attribute. If the property does not exist, a new property is created.

Delattr (obj, name): deletes an attribute.

Python built-in class attributes

_ Dict _: class attributes (including a dictionary consisting of class data attributes)

_ Doc _: Document string of the class

_ Name __: Class name

_ Module __: module where the class definition is located (the full name of the class is '_ main __. classname'. If the class is located in mymod of an import module, then className. _ module _ equals to mymod)

_ Bases _: Elements of all parent classes of the class (including tuples consisting of all parent classes)

Class Person: "Person class" def _ init _ (self, name, age, gender): print ('entry to Person initialization') self. name = name self. age = age self. gender = gender print ('exit Person initialization') def getName (self): print (self. name) p = Person ('ice ', 18, 'male') print (p. name) # iceprint (p. age) #18 print (p. gender) # MALE print (hasattr (p, 'weight ') # False # Add the weight attribute p for p. weight = '000000' print (hasattr (p, 'weight') # Trueprint (getattr (p, 'name') # iceprint (p. _ dict _) # {'age': 18, 'Gender ': 'male', 'name': 'ice'} print (Person. _ name _) # Personprint (Person. _ doc _) # Person class print (Person. _ dict _) # {'_ doc _': 'person class', '_ weakref __': <attribute '_ weakref _' of 'person 'objects>,' _ init _ ': <function Person. _ init _ at 0x000000000284E950>, 'getname': <function Person. getName at 0x000000000284EA60>, '_ dict _': <attribute '_ dict _' of 'others' objects>, '_ module __': '_ main _'} print (Person. _ mro _) # (<class '_ main __. person '>, <class 'object'>) print (Person. _ bases _) # (<class 'object'>,) print (Person. _ module _) # _ main __

Class Method

Inside the class, you can use the def keyword to define a method for the class. Unlike the general function definition, the class method must contain the self parameter and be the first parameter.

Class proprietary method:

_ Init _ constructor called when an object is generated

_ Del _ destructor used to release objects

_ Repr _ print, convert

_ Setitem _ assign values based on the index

_ Getitem _ obtain the value based on the index

_ Len _ Get the length

_ Cmp _ comparison Calculation

_ Call _ function call

_ Add _ addition operation

_ Sub _ Subtraction

_ Mul _ Multiplication operation

_ Div _ division operation

_ Mod _ remainder operation

_ Pow _ caller

The _ init _ () method is a special method called a class constructor or initialization method. This method is called when an instance of this class is created, similar to constructor in c ++. You only need to override the _ init _ () method in the Custom class.

Class Person: def _ init _ (self, name, age, gender): print ('initialize Person ') self. name = name self. age = age self. gender = gender print ('exit Person initialization') def getName (self): print (self. name) # Person Instance Object p = Person ('ice ', 18, 'male') print (p. name) print (p. age) print (p. gender) p. getName () # initialize the Person entry # initialize the Person exit # ice #18 # male # ice

Destructor _ del _ ,__ del _ is called when the object disappears. When the object is no longer used, run the __del _ method:

Method

Instance method: it can only be called by an instance. The first defined parameter of an instance method can only be referenced by the instance itself.

Class Myclass: def foo (self): print (id (self), 'foo') a = Myclass () # since it is an instance object, create instance. foo () # print (id (a) function address in the output class # address of the output class Object # Same result address

Class Method: defines a class method. To use the decorator @ classmethod, the first parameter defined can be a reference to a class object, which can be directly used by a class or instance.

Class Myclass: @ classmethod # class decorator def foo2 (cls): print (id (cls), 'foo2') # class object, which can be called directly, print (id (Myclass), 'yy') Myclass does not need to be instantiated. foo2 () # can be called directly

Static Method: defines the static method to use the decorator @ staticmethod. No default parameter is required. It is called directly through classes and instances.

Class Myclass: @ staticmethod # static method def foo3 (): print ('foo3') Myclass. foo3 () # No parameter a. foo3 () # result foo3

Class Encapsulation

Python uses variable names to differentiate access permissions for attributes and methods. The default permission is equivalent to public in c ++ and java.

Private Attribute of the class: _ private_attrs: It starts with two underscores. It is declared as private and cannot be used outside the class or accessed directly. Self. _ private_attrs is used in internal methods of the class.

Class private method :__ private_method: starts with two underscores and declares this method as a private method. It cannot be called outside the class. Call self. _ private_methods inside the class

Although python does not allow the instantiated class to access private data, you can use object. _ className _ attrName to access the attribute. In fact, the implementation of python's internal privatization only changes the attrName attribute to _ className _ attrName.

Class Demo: _ id = 123456 def getId (self): return self. _ idtemp = Demo () # print (temp. _ id) # AttributeError: 'Demo' object has no attribute '_ id' print (temp. getId () #123456 print (temp. _ Demo _ id) #123456

Class inheritance

One of the main benefits of object-oriented programming is code reuse. One of the ways to achieve this reuse is through the inheritance mechanism. Inheritance can be fully understood as the relationship between types and subtypes between classes.

Note: inherited syntax class derived class name (base class name )://... in the base class name writing brackets, the basic class is specified in the tuples when the class is defined.

Some features of inheritance in python:

1: The Construction (_ init _ () method) of the base class in the inheritance class will not be automatically called. It needs to be called in the construction of its derived class. Use super (). _ init _ () or parentClassName. _ init __()

2: when calling a base class method, you must add the base class name prefix and the self parameter variable. Unlike calling a common function in a class, the self parameter is not required.

3: Python always first looks for the corresponding type of method. If it cannot find the corresponding method in the derived class, it starts to look for it one by one in the base class. (Search for the called method in this class before finding it in the base class ).

If more than one class is listed in the inheritance tuples, it is called "Multi-inheritance ".

Syntax:

Similar to their parent class, the list of inherited base classes follows the class name.

Polymorphism

If the function of the parent class method cannot meet the requirements, you can override the method of the parent class in the subclass. When an instance object calls a method, it will call the override method of its corresponding subclass.

Python3.3 class and inheritance example

Classes in hon provide all the basic functions of object-oriented programming: The Inheritance Mechanism of classes allows multiple base classes. Derived classes can override any methods in the base class, you can call methods of the same name in the base class.

class Base:  def __init__(self):    self.data=[]  def add(self,x):    self.data.append(x)  def addtwice(self,x):    self.add(x)    self.add(x)# child extends baseclass Child(Base):  def plus(self,a,b):    return a+boChild=Child()oChild.add("str1")oChild.add(999)oChild.addtwice(4)print(oChild.data)print(oChild.plus(2,3))

Objects can contain any number of data types.

Similar to c ++, python classes provide class encapsulation, inheritance, multi-inheritance, constructor, and destructor.

In python3, the top-level parent class of all classes is an object class. Similar to java, if the parent class is not written during class definition, the object class is its direct parent class.

Class Definition

The syntax format of the class definition is as follows:

class ClassName:<statement-1>...<statement-N>

Class Object: after creating a class, you can access and change its attributes and methods by class name.

Instance Object: after the class is instantiated, you can use its attributes to dynamically add attributes (similar to javascript) to the instance object without affecting the class object.

Class attributes

You can use vertex (.) to access object attributes.

You can also use the following functions to access attributes:

Getattr (obj, name [, default]): Access Object Attributes

Hasattr (obj, name): Check whether an attribute exists.
Setattr (obj, name, value): sets an attribute. If the property does not exist, a new property is created.

Delattr (obj, name): deletes an attribute.

Python built-in class attributes

_ Dict _: class attributes (including a dictionary consisting of class data attributes)

_ Doc _: Document string of the class

_ Name __: Class name

_ Module __: module where the class definition is located (the full name of the class is '_ main __. classname'. If the class is located in mymod of an import module, then className. _ module _ equals to mymod)

_ Bases _: Elements of all parent classes of the class (including tuples consisting of all parent classes)

Class Person: "Person class" def _ init _ (self, name, age, gender): print ('entry to Person initialization') self. name = name self. age = age self. gender = gender print ('exit Person initialization') def getName (self): print (self. name) p = Person ('ice ', 18, 'male') print (p. name) # iceprint (p. age) #18 print (p. gender) # MALE print (hasattr (p, 'weight ') # False # Add the weight attribute p for p. weight = '000000' print (hasattr (p, 'weight') # Trueprint (getattr (p, 'name') # iceprint (p. _ dict _) # {'age': 18, 'Gender ': 'male', 'name': 'ice'} print (Person. _ name _) # Personprint (Person. _ doc _) # Person class print (Person. _ dict _) # {'_ doc _': 'person class', '_ weakref __': <attribute '_ weakref _' of 'person 'objects>,' _ init _ ': <function Person. _ init _ at 0x000000000284E950>, 'getname': <function Person. getName at 0x000000000284EA60>, '_ dict _': <attribute '_ dict _' of 'others' objects>, '_ module __': '_ main _'} print (Person. _ mro _) # (<class '_ main __. person '>, <class 'object'>) print (Person. _ bases _) # (<class 'object'>,) print (Person. _ module _) # _ main __

Class Method

Inside the class, you can use the def keyword to define a method for the class. Unlike the general function definition, the class method must contain the self parameter and be the first parameter.

Class proprietary method:

_ Init _ constructor called when an object is generated

_ Del _ destructor used to release objects

_ Repr _ print, convert

_ Setitem _ assign values based on the index

_ Getitem _ obtain the value based on the index

_ Len _ Get the length

_ Cmp _ comparison Calculation

_ Call _ function call

_ Add _ addition operation

_ Sub _ Subtraction

_ Mul _ Multiplication operation

_ Div _ division operation

_ Mod _ remainder operation

_ Pow _ caller

The _ init _ () method is a special method called a class constructor or initialization method. This method is called when an instance of this class is created, similar to constructor in c ++. You only need to override the _ init _ () method in the Custom class.

Class Person: def _ init _ (self, name, age, gender): print ('initialize Person ') self. name = name self. age = age self. gender = gender print ('exit Person initialization') def getName (self): print (self. name) # Person Instance Object p = Person ('ice ', 18, 'male') print (p. name) print (p. age) print (p. gender) p. getName () # initialize the Person entry # initialize the Person exit # ice #18 # male # ice

Destructor _ del _ ,__ del _ is called when the object disappears. When the object is no longer used, run the __del _ method:

Class Encapsulation

Python uses variable names to differentiate access permissions for attributes and methods. The default permission is equivalent to public in c ++ and java.

Private Attribute of the class: _ private_attrs: It starts with two underscores. It is declared as private and cannot be used outside the class or accessed directly. Self. _ private_attrs is used in internal methods of the class.

Class private method :__ private_method: starts with two underscores and declares this method as a private method. It cannot be called outside the class. Call self. _ private_methods inside the class

Although python does not allow the instantiated class to access private data, you can use object. _ className _ attrName to access the attribute. In fact, the implementation of python's internal privatization only changes the attrName attribute to _ className _ attrName.

Class Demo: _ id = 123456 def getId (self): return self. _ idtemp = Demo () # print (temp. _ id) # AttributeError: 'Demo' object has no attribute '_ id' print (temp. getId () #123456 print (temp. _ Demo _ id) #123456

Class inheritance

One of the main benefits of object-oriented programming is code reuse. One of the ways to achieve this reuse is through the inheritance mechanism. Inheritance can be fully understood as the relationship between types and subtypes between classes.

Note: inherited syntax class derived class name (base class name )://... in the base class name writing brackets, the basic class is specified in the tuples when the class is defined.

Some features of inheritance in python:

1: The Construction (_ init _ () method) of the base class in the inheritance class will not be automatically called. It needs to be called in the construction of its derived class. Use super (). _ init _ () or parentClassName. _ init __()

2: when calling a base class method, you must add the base class name prefix and the self parameter variable. Unlike calling a common function in a class, the self parameter is not required.

3: Python always first looks for the corresponding type of method. If it cannot find the corresponding method in the derived class, it starts to look for it one by one in the base class. (Search for the called method in this class before finding it in the base class ).

If more than one class is listed in the inheritance tuples, it is called "Multi-inheritance ".

Syntax:

Similar to their parent class, the list of inherited base classes follows the class name.

Polymorphism

If the function of the parent class method cannot meet the requirements, you can override the method of the parent class in the subclass. When an instance object calls a method, it will call the override method of its corresponding subclass.

Python3.3 class and inheritance example

class Base:def __init__(self):self.data=[]def add(self,x):self.data.append(x)def addtwice(self,x):self.add(x)self.add(x)# child extends baseclass Child(Base):def plus(self,a,b):return a+boChild=Child()oChild.add("str1")oChild.add(999)oChild.addtwice(4)print(oChild.data)print(oChild.plus(2,3))

The above description of attributes, methods, encapsulation, and inheritance instances based on the python3 class is all the content that I have shared with you. I hope to give you a reference and support for the customer's house.

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.