Attributes, methods, encapsulation, inheritance, and small instances of Python3 classes

Source: Internet
Author: User
Tags access properties class definition function definition inheritance in python

Python class

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

An object can contain any number and type of data.

Python classes are similar to C + + classes, providing encapsulation of classes, inheritance, multiple inheritance, constructors, destructors.

In Python3, the top-level parent class of all classes is the object class, similar to Java, if the class is defined without writing out the parent class, then the object class is its immediate parent class.


class definition

The class definition syntax format is as follows:

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

Class object: After you create a class, you can access it by class name, change its properties, method

Instance object: When a class is instantiated, its properties can be used to dynamically add properties (like JavaScript) to instance objects without affecting class objects.


properties of the class

You can use dots (.) To access the properties of the object

You can also access properties by using the following functions:

GetAttr (obj, name[, default]): Accessing the properties of an object

Hasattr (obj,name): Check that there is a property
SetAttr (Obj,name,value): Sets a property. If the property does not exist, a new property is created

Delattr (obj, name): deleting attributes



Python Built-in class properties

__DICT__: The properties of the class (including a dictionary, consisting of the data properties of the Class)

__DOC__: Document string for Class

__NAME__: Class name

__MODULE__: The module where the class definition resides (the full name of the class is ' __main__.classname ', and if the class is in an import module mymod, then classname.__module__ equals Mymod)

__bases__: All the parent classes of a class constitute elements (including a tuple of all parent classes)

Class person:      "Person class"     def __init__ (Self, name,  age, gender):         print (' Initialize of person ')          self.name = name          Self.age = age         self.gender = gender  
       print (' Departure from person initialization ')     def getname (self):
        print (self.name) P = person (' Ice ', 18,  ' man ') Print (p.name)   # ice print (p.age)   # 18 print (p.gender)   #  male print ( Hasattr (p,  ' weight '))   # false #  Add weight attribute p.weight =  ' 70kg ' Print (hasattr ( p,  ' weight ')   # true print (GetAttr (p,  ' name '))   # ice print (p.__dict__)  # {' age ': 18,  ' gender ':  ' man ',  ' name ':  ' Ice '} print (person.__name__)   # person print (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  ' person '  objects>,  ' module__ ':  ' __main__ '} print (person.__mro__)   #  (<class  ' __main__. Person ' >, <class  ' object ' > ' Print (person.__bases__)   #  (<class  ' Object ', ' Print (person.__module__)   # __main__

Methods of the


class

inside the class, use the DEF keyword to define a method for the class, unlike a general function definition, the class method must contain the parameter self and the first argument. The proprietary methods of the

 

Class:

    __init__ constructors, calling

    __del__ When the object is generated destructors, using

    __repr__ Printing when releasing objects, converting

    __setitem__ by index

     __getitem__ Get the value by index

    __len__ get length

    __cmp__ comparison Operation

    __call__ function calls

    __add__ Add operations

    __sub__ subtraction

    __mul__ multiplication

    __div__ excluding operations

    __mod__ remainder Operations
The
    __pow__

 

__init__ () method is a special method, called the constructor or initialization method of a class, that is invoked when an instance of the class is created. Similar to constructors in C + +. Simply rewrite the __init__ () method in the custom class.

class person:     def __init__ (Self,  name, age, gender):         print (' Initialize of person ')          self.name = name        
 self.age = age         self.gender = gender         print (' Departure from person's initialization ')     def getname ( Self):         print (Self.name) # person Instance Object P = Person (' Ice ', 18,  ' man ') print (p.name) print (p.age) print (P.gender) p.getname () #  Enter the initialization of person #  Leave the initialization of person # ice # 18 #  male # ice 


destructor __del__, __del__ is invoked when the object dies, and the __del__ method runs when the object is no longer in use:


Encapsulation of a class

Python distinguishes properties and methods by naming them by variable names, which are equivalent to public in C + + and Java


The private property of the class: __private_attrs: Two underscore starts with a declaration that the property is private and cannot be used or accessed directly from outside the class. Self.__private_attrs when used in methods inside a class.

The private method of a class: __private_method: Two underscore starts, declares that the method is a private method, and cannot be invoked outside of the class. Calling Self.__private_methods inside a class


Although Python does not allow instantiated classes to access private data, it can use Object._classname__attrname to access properties. In fact, the implementation of Python internal privatization is only the Attrname attribute into a _classname__attrname just

Class Demo:
__id = 123456
def getId (self): return
self.__id
temp = Demo ()
# Print (temp . __id) # error Attributeerror: ' Demo ' object has no attribute ' __id '
print (Temp.getid ()) # 123456
print (temp._demo_ _ID) # 123456


Inheritance of Classes

One of the main benefits of object-oriented programming is the reuse of code, one of the ways to achieve this reuse is through inheritance mechanisms. Inheritance can be fully understood as a type and subtype relationship between classes.

What to note: Inheritance syntax class derived class name (base class name)://... base class name writing parentheses, the base class is specified in the tuple when the class is defined.

Some of the features of inheritance in Python:

1: The construction of the base class (__init__ () method) in inheritance is not invoked automatically, and it needs to be specifically invoked in the construction of its derived class. Use Super (). __init__ () or parentclassname.__init__ ()
2: When calling a method of a base class, you need to prefix the class name of the base class with the Self argument variable. Unlike calling a normal function in a class, you do not need to take the self argument
3:python always first finds a method of the corresponding type, and if it cannot find the corresponding method in the derived class, it begins to look in the base class individually. (Find the Called method first in this class and find it in the base class.)

If more than one class is listed in the inheritance tuple, it is called "Multiple inheritance."

Grammar:

The declaration of a derived class, similar to their parent class, is followed by a list of inherited base classes after the class name.

Polymorphic

If the function of the parent class method does not meet the requirement, you can override the parent class's method in the subclass. When an instance object invokes a method, it invokes the overridden method of its corresponding subclass


python3.3 class vs. inherited small example

class Base:
    def __init__ (self):
   & nbsp;    self.data=[]
    def Add (self,x):
        self.data.append (x)
    def addtwice (self,x):
         Self.add (x)
        self.add (x)

# Child extends Base
Class child (base):
    def Plus (self,a,b):
        return a+b

Ochild=child (
Ochild.add ("str1")
Ochild.add (999)
Ochild.addtwice (4)
Print (ochild.data)
Print (Ochild.plus ( 2, 3))

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.