Python Learning Notes 6.2-class common programming patterns

Source: Internet
Author: User

The last time I wrote a blog about Python, now look back and find a lot of grammar or low-level, the expression is not very clear. Now let's talk about a new understanding of the expression of the Python class.
The focus of this blog is to introduce some of the common programming patterns associated with class definitions, mainly including enabling objects to support common Python features, the use of special methods, encapsulation, inheritance, memory management, and some useful design patterns. 1 Modifying the string representation of an instance

In the definition of the Python class, we can implement the string output of the instance by defining the __repr¬¬__ () method and the __str__ () method

1.1 Special Method repr() returns the code representation of the instance, that is, to recreate the instance through the string literal returned by him, that is, to satisfy obj = eval (repr (obj)). However, if this condition is not possible, it would be better for him to produce a helpful text and express it in the form of a < document >.
The 1.2 str() method is better understood by converting an instance to a string and doing it as a print output, which means that what you want print () output is defined in str().

Class point:
    def __init__ (self,x,y):
        self.x = x
        self.y = y-
    def __repr__ (self): return
        ' point ({0.x! R},{0.y!r}) '. Format (self)

    def __str__ (self): return
        ' ({0.x!s},{0.y!s}) '. Format (self)

a
out[3 ]: Point 
(3,4)

print (a)
(3,4)

From this example we can see the difference between the two. Special attention is paid to: (1). R is dedicated to repr(), generally not in str() (2) on the format () formatted output will be dedicated to write a blog to introduce, its role is very powerful. (3) 0 represents self. 0.x is similar to self.x and super (). 2 output format for custom strings

The format () function and the string method enable you to implement a custom output format for an object, simply by adding the format() method to the definition of the class.

_formats = {
    ' ymd ': ' {d.year}-{d.mouth}-{d.day} ',
    ' mdy ': ' {d.mouth}/{d.day}/{d.year} ',
    ' dmy ': ' {d.day}/ {d.mouth}/{d.year} '
            }
class Date:
    def __init__ (self,year,mouth,day):
        self.year =
        Year Self.mouth = mouth
        self.day = Day

    def __format__ (self,code):
        If code = = ':
            code = ' Ymd ' fmt
        = _f Ormats[code] Return
        fmt.format (d=self)
a = Date (2013,3,5) print (format (
a))
print (Format (a), ' Mdy '))
print (Format (A, ' dmy '))

format () method provides a hook in the Python string formatting feature, and the content of the formatted output depends entirely on the class itself, which is the programmer customization. In general, formatting code can be any form. 3 Let object support context management Protocol

Objects in Python can support the context Management Protocol (Context_management Protocol), which is triggered by the WITH statement, which is to create the object when entering the WITH statement and destroy the object when exiting the With statement.
Python uses the enter() method and the Exit() method to implement this functionality in the definition of a class.

#-----------------------------------------------------------
# Here's an example                        |
#-----------------------------------------------------------
4 Save memory with slot method

For classes that are used as simple data structures, it is often possible to add slot() methods to reduce their use of memory. When the slot() method is defined, Python uses a more compact internal structure representation for the instance, no longer allowing each instance to create a dict dictionary. The disadvantage of using the slot() method is that you can no longer add new properties to the instance, only the attributes that are written at the time of the definition are used.
Slot () method is generally regarded as a Python optimization method, and of course sometimes used to constrain a program to prevent users from adding new attributes to the instance.

#-----------------------------------------------------------
# Here's an example                        |
#-----------------------------------------------------------
5 Encapsulation of Python classes

"Encapsulation" is the combination of abstract data and behavior (or functionality), form an organic whole (ie class); The purpose of encapsulation is to enhance security and simplify programming, the user does not need to understand the specific implementation details, but only through the external interface, specific access rights to use the members of the class.
Unlike other programming languages that encapsulate classes with other language features, Python uses specific naming conventions to express the use of data and methods. (1) Any name that begins with a double underline (__) belongs to a private property or method and can only be invoked in the class, without being invoked or inherited externally. This rule also applies to the definition of blocks and the definition of functions in modules.

Class A:
    def __init__ (self):
        self.__private = 0 #私有属性
        self.public    = 0 #公有属性

    def public_method (self ): #公有方法
        ': return

        : ' '
        print (' The ' is a public method ')

    def __private_method (self): #私有方法
        ' '

        : return:
        ' '
        print (' The ' is a private method ')

a = A ()
A.public_method ()
a._ _private_method ()  #会报错
Print (a.__private)    #会报错

Traceback (most recent call last):
  File "D :/home/wx/test_clsaa.py ", line, in <module>
    A.__private_method ()
attributeerror: ' A ' object has no Attribute ' __private_method '

However, it is also possible to access private properties if you must. Use: Instance name. _ Class Name private property name (for example: a._a__private) can be accessed.

Class A:
    def __init__ (self):
        self.__private = 0 #私有属性
        self.public    = 0 #公有属性

    def public_method (self ): #公有方法
        ': return

        : ' '
        print (' The ' is a public method ')

    def __private_method (self): #私有方法
        "'

        : return:
        ' '
        print (' The ' is a private method ')

a = A ()
print (a._a__private)
A._a__private_method ()

0 This are
A private method

Similarly, private properties and methods cannot be inherited by the quilt class and will not be overwritten by quilts.

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.