Python learning notes 1: Data Models and special methods (magic methods), python learning notes

Source: Internet
Author: User

Python learning notes 1: Data Models and special methods (magic methods), python learning notes

First, put your personal website: www.comingnext.cn.

1. Data Model

In the official Python documentation, this is the case:

The object is Python's data abstraction. All data in a Python program is expressed by the relationship between objects or objects. In a sense, in order to be consistent with the computer model of the Von noriman storage program, code and data are also an object (as mentioned in the von noriman model, data and programs are both stored in memory as 0, 1)

Simply put, all data in Python is either an object or an object.

If you enter the world of Python with experience from other object-oriented languages, you will feel uncomfortable writing len (object) instead of ** object. len. But it embodies a design concept of Python, which is also the key of pythonic. This idea is embodied in the Python data model.

The data model is actually a description of the Python framework. It standardizes the interfaces of the modules built by the language itself. These modules include but are not limited to sequences, iterators, functions, classes, and context managers.

2. Special Methods (magic methods)

Regardless of the framework in which the program is written, it will take a lot of time to implement the methods that will be called by the framework itself, and Python is no exception.

When the Python interpreter encounters special syntaxes, it uses special methods to activate some basic object operations. The names of these special methods start with two underscores, end with two underscores (for example, _ getitem __). For example, the _ getitem _ method is behind obj [key]. To obtain the value of my_collection [key], the interpreter actually calls my_collection._ Getitem_ (Key ). Magic method is the nickname of a special method. The special method is also called the double-bottom method ).

By implementing special methods, custom data types can behave the same as built-in data types, so that we can write code that is more expressive-or, more Python-style code. For example, the following code:

 1 import collections 2  3 Card = collections.namedtuple('Card', ['rank', 'suit']) 4  5 class FrenchDeck: 6     ranks = [str(n) for n in range(2, 11)] + list('JQKA') 7     suits = 'spades diamonds clubs hearts'.split() 8  9     def __init__(self):10         self._cards = [Card(rank, suit) for suit in self.suits11                                         for rank in self.ranks]12 13     def __len__(self):14         return len(self._cards)15 16     def __getitem__(self, position):17         return self._cards[position]

 

This code is a prototype of playing cards. In this custom class, there are three special methods we have written. Through these methods, our custom classes can be used like Python's built-in classes. Save the Code as the frenchdeck. py file, and enter the directory where the file is located in the command line window. Python3 and Python2 are used here.

Enter the Python shell as follows:

Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> from frenchdeck import *>>> deck = FrenchDeck()>>> len(deck)52>>> deck[0]Card(rank='2', suit='spades')>>> deck[-1]Card(rank='A', suit='hearts')>>>

 

Through the example above, we can see that when we use len (deck) and deck [0, the Python interpreter actually calls the _ len _ and _ getitem _ methods in the Custom class.

Then, if we want to randomly extract a card from this deck of cards, what should we do? Are you writing a method yourself? This is not required in Python. Python has built in the random function that randomly selects an element from a sequence. choice, we just need to use it on this card stack instance (the interpreter code is connected ):

>>> from random import choice >>> choice(deck)Card(rank='3', suit='hearts') >>> choice(deck)Card(rank='K', suit='spades') >>> choice(deck)Card(rank='2', suit='clubs')

 

Through the two examples above, we can see two advantages of using the Python data model by implementing special methods:

1. as users of your class, they don't have to remember the names of standard operations ("How To Get The total number of elements? Is it. size (),. length (), or something else ?").

2. It is easier to use Python's standard library, such as the random. choice function, without re-inventing the wheel.

At the same time, we can also understand that the calls to these special methods are usually implicit. First of all, it is clear that the existence of special methods is called by the Python interpreter, you do not need to call them. That is to say, you should use len (my_object) instead of my_object. _ len ). When executing len (my_object), if my_object is a custom Class Object, Python calls the _ len _ method implemented by you. Using built-in functions (such as len, iter, str, and so on) is the best choice. These built-in functions call not only special methods, but also provide additional benefits. They are faster for built-in classes.

There are many special methods for Python data models. For more information about Python data models and special methods, see https://docs.python.org/3/reference/datamodel.html, which is the most compatible pythonknowledge library.

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.