Object representation

Every object-oriented language has at least one standard way to get the string representation of an object .Python It provides two ways

repr()

Returns the string representation of the object in a way that is easy for developers to understand

str()

Returns the string representation of the object in a way that is easy for the user to understand .

As you know , We want to achieve __repr__ and __str__ Special methods , by repr() and str() Provide support .

Talking about vector class again

To illustrate the many methods used to generate object representations , We will use a Vector2d class . This and the following sections will continue to implement this class . We expect Vector2d The basic behavior of an instance is as follows .

Vector2d Instances can be expressed in many ways

>>> v1 = Vector2d(3, 4)
>>> print(v1.x, v1.y) #Vector2d The components of an instance can be accessed directly through attributes
3.0 4.0
>>> x, y = v1 #Vector2d Instances can be unpacked into variable primitives
>>> x, y
(3.0, 4.0)
>>> v1 #repr Function call Vector2d example , The result is similar to the source code of the instance
Vector2d(3.0, 4.0)
>>> v1_clone = eval(repr(v1)) # Use here eval function , indicate repr Function call Vector2d The example is an accurate description of the construction method
>>> v1 == v1_clone #Vector2d Examples support the use of == Compare ; It's easy to test
True
>>> print(v1) #print Function will call str function , Yes Vector2d Come on , The output is an ordered pair
(3.0, 4.0)
>>> octets = bytes(v1) #bytes Function will call __bytes__ Method , Generate the binary representation of the instance
>>> octets
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
>>> abs(v1) #abs Function will call __abs__ Method , return Vector2d Modules of instances
5.0
>>> bool(v1), bool(Vector2d(0, 0)) #bool Function will call __bool__ Method , If Vector2d The module of the instance is zero , Then return to False, Otherwise return to True

vector2d_v0.py How to achieve

 from array import array
import math class Vector2d:
typecode = 'd' # Class properties def __init__(self, x, y): # Constructors , Instantiation takes two parameters ,x and y, Turn into float type
self.x = float(x)
self.y = float(y) def __iter__(self): # Support iterative , That is to support the unpacking operation outside for example ,x, y = my_vector
return (i for i in (self.x, self.y)) def __repr__(self): #__repr__ Methods use {!r} Get the representation of each component , And then interpolation ,
class_name = type(self).__name__ # Form a string ; because Vector2d Instances are iterative objects , therefore
return '{}({!r}, {!r})'.format(class_name, *self) # *self Will be able to x and y Components are provided to format function def __str__(self): # From the iterative Vector2d In the example, you can easily get a tuple , Show as an ordered pair
return str(tuple(self)) def __bytes__(self):
return (bytes([ord(self.typecode)])+ # To generate a sequence of bytes , We put typecode Convert to a sequence of bytes
bytes(array(self.typecode, self))) # iteration Vector2d example , Get an array , And then convert the array into a sequence of bytes def __eq__(self, other): # To quickly compare all components , Building tuples in operands
return tuple(self) == tuple(other) def __abs__(self): # The model is x and y The oblique side length of a right triangle made up of components
return math.hypot(self.x, self.y) def __bool__(self): #__bool__ Methods use abs(self) Computational model , Then convert the result to a Boolean value , therefore ,0.0 yes False, The nonzero value is True.
return bool(abs(self))

Alternative construction methods

We can Vector2d The instance is converted to a sequence of bytes ; Empathy , It should also be able to convert from byte sequence to Vector2d example . We used it before array.array There's a class method .frombytes.

python accord with Python More articles about the object of style

  1. smooth python accord with python The object of style

    Object representation Every object-oriented language has at least one standard way to get the string representation of an object .Python It provides two ways . repr() Returns the string representation of an object in a way that is easy for developers to understand .str() To make it easy for users to understand ...

  2. The first 9 Chapter accord with Python The object of style

    #< smooth Python> Reading notes # The first 9 Chapter accord with Python The object of style # This chapter contains the following topics : # Supports built-in functions for generating other representations of objects ( Such as repr().bytes(), wait ) # send ...

  3. Fluent_Python_Part4 object-oriented ,09-pythonic-obj,Python The object of style

    The fourth part is 9 Chapter ,Python The object of style This chapter goes on to 1 Chapter , Explain the common special methods to realize . This chapter includes the following topics : Supports built-in functions for generating other representations of objects ( Such as repr().bytes(), wait ) Use a class method to implement ...

  4. Python PEP-8 Chinese version of coding style guide

    #PEP 8 – Python Coding style guide PEP: 8 Title: Style Guide for Python Code Author: Guido van Rossum , Barry War ...

  5. Python Basic grammar 07-- object-oriented + Regular expressions

    Python object-oriented Python It has been an object-oriented language since the beginning of design , Because of that , stay Python It's easy to create a class and object in . In this chapter, we will introduce it in detail Python Object - oriented programming . If you haven't touched it before ...

  6. Python iterator , Iteratable object , generator

    iterator iterator (iterator) Sometimes called cursor (cursor) It's the software design pattern of programming , It can be used in containers (container, Like linked lists or arrays ) Last visit interface , Designers don't need to care about the implementation details of memory allocation for container objects . ...

  7. Python Iteratable objects and iterator objects in

    Just learning Python, Yes “ Iteratable object ” and " Iterator object " Personal understanding of , I don't know . 1. Several concepts (1) Iteration tools : Include for loop . List of analytical .in Membership testing ..... And so on , be used for ...

  8. python Learning notes 4( object / quote ; Multiple paradigm ; Context manager )

    ### Python A big part of the strength of the game is , It offers a lot of written , Ready to use objects 21. Dynamic type : object / quote Objects and references : An object is an entity stored in memory , The object name is just a reference to the object (refere ...

  9. python Class in , object , Method , Properties, etc

    notes : This article is well written . Shading is my own understanding python Everything is an object , The object : I am an object myself , The computer I play with is the object , The chair is the object , The dog at home is also an object ...... By describing properties ( ...

Random recommendation

  1. struts2 Study notes 2 : Basic environment construction

    Study struts2 It's been a while , As an operation and maintenance personnel, the study time is very tight , Write this document for the convenience of future review Environmental Science : MyEclipse 10 tomcat6 jdk1.6   So let's set up a web project , and ...

  2. On the client side csdn The list of articles under different categories on ( Make csdn app 3、 ... and )

    Reprint please indicate the source :http://blog.csdn.net/lmj623565791/article/details/23597229 Today will be in Android Use Fragment,ViewPagerI ...

  3. PLSQL DEVELOPER Some of the techniques used 【 turn 】

    1. Automatically selected by default after login My Objects By default ,PLSQL Developer After logging in ,Brower I will choose All objects, If the user you log in to is dba, To expand tables Catalog , Under normal circumstances, we need ...

  4. from 0 To 1 use eclipse use maven build web project

    1, The default has been set up JDK1.5 above , as well as eclipseEE edition , and maven. 2, modify maven Local warehouse and image of , Modify the local warehouse to facilitate our management ,maven The default warehouse for is C Discoid USER Under the folder , I just ...

  5. Python_ Document processing

    1.Python  Document processing Open file ----> Read the content ----> Get content How to read files :  r  Read only file   w Write only mode a Append mode r+b Read write mode    w+b Read write mode   a+b ...

  6. JWT(JSON Web Token)

    Abstract : stay Web Application , Use JWT replace session It's not a good idea fit JWT Usage scenarios of I'm sorry , Back to the title party . I don't deny JWT The value of , It's just that it's often misused . What is? JWT According to Wikipedia ,JSON W ...

  7. AC Automata related Fail Trees and Trie The basic knowledge of graph

    Loaded from 55242 character string AC Automata column fail Trees Definition Put all the fail The pointer is reversed , So you get a tree ( Because the degree of each node is 1, So after reversing, the penetration of each node is 1, So what you get is a tree ) Repayment - With this thing , ...

  8. Linux Learning notes ( The fifth chapter )

    The fifth chapter - Commonly used instructions An order : 1.[Tab] 2.man + ( Instructions ): Show operating instructions The opening code man page Common buttons

  9. Linux Study ——echo and read Command usage

    Reprinted from http://www.runoob.com/linux/linux-comm-read.html http://www.178linux.com/76331 echo command This article lists echo command ...

  10. DelphiXE8 How to use debug mode ( Mi phones 2)

    demand : Developing Android The program , People have been using ShowMessage. Actually XE It supports the next breakpoint . operation : Mi phones 2: 1. Mi phones 2 use USB Line , Connect to the computer . 2. Mi phones 2- Set up - About mobile phone -" ...