The 9th chapter meets the Python-style object __python

Source: Internet
Author: User
Tags abs hypot ord time and date

The harder you work, the luckier you will be. Come on!!! 9.1 Representation of Objects

A method of implementing a two-dimensional vector for a custom class:

From array import array import math class vector2d: "" to implement a two-dimensional vector "" typecode = ' d ' def __init__ (self, x, y): self.x = float (x) self.y = float (y) def __iter__ (self): "" "" "to the vector2d into an iterative object, so that the calculation of the unpacking
        "" "Return (I to I in (self.x, SELF.Y)) def __repr__ (self): class_name = Type (self). __name__ Return ' {} ({!r}, {!r}) '. Format (class_name, *self) def __str__ (self): Returns STR (tuple (self)) # What do you mean, back here?

    ???
        def __bytes__ (self): return (Bytes[ord (Self.typecode)]) # Ord returns a Unicode-type byte def __eq__ (self, Other):  "" "" "can be compared only when two objects are vector2d" "" Return tuple (self) = = Tuple (other) def __abs__ (self): return Math.hypot (self.x, SELF.Y) # Hypot is the result of the calculation x*2 + y*2 def __bool__ (self): return bool (ABS (self)) def __ Format__ (Self, fmt_spec= ""): "" "the form of the format format of the custom class, which controls the result" "of the custom formatting of the class by implementing the __format__ form" "Components = (format (c, Fmt_spec) For C in self) return "({}, {})". Format (*components) 

Gets the method of the object string form;
1. REPR ()
A way to understand the point of view of the developer returns the representation of the string of the object
2. STR ()
Returns the form of a string of objects in a form that the user can easily understand
Call relationships for functions and built-in functions
1. The print function calls the STR function
2. The bytes function invokes the bytes method to generate the binary representation of the instance.
3. Abs function will call abs method
4. The BOOL function invokes the bool method
5. Use Type (object). __name__ can get the name of the type of the object
6. Object.__dict__ can obtain information such as the properties of the object, class.__dict__ can get all the properties of the class, and the method
7. If you rewrite the method methods in Python in a class , when you use a built-in function, you automatically invoke the method overridden in this class to return the value 9.4 classmethod and Staticmethod

Classmethod defines an action class instead of an object, passing in the self example of an object, Classmethod changes the way the call is made, the first parameter is the class itself, not the example. The most common use of classmethod is to define alternative construction methods

If you need to use a class variable in the method, you need to use the Classmethdo adorner, staticmethod in fact, just for the purpose of, to the class to use, where the parameters, no class variables and sample variables formatted display

The built-in format () function, and the Str.format () method delegate the format of each type to the __format__ (Format_spec) method of the response, Format_spec is the format specifier, which is:
1. The second parameter of format (Mg_obj, Format_spec), or
2. Str.format () method of the format string, {} In the substitution field after the colon to buy the part

B1 = 1/2.34

B1
out[2]: 0.4273504273504274

Format (B1, ' 0.4f ')
out[3]: ' 0.4274 ' '

{rate:0.2f} '. Format (RATE=B1)  # uses the established fields to make the part that needs to be formatted
out[4]: ' 0.43 '
# The string above contains two parts, the first is the specified and subsequent field names, and the second is the format specifier


Format ("B")
Out[6]: ' 101011 '

format (2/3, ". 1%")
out[7]: ' 66.7% '

Format time and date using format

From datetime import datetime now

= DateTime.Now ()

now
out[10]: Datetime.datetime (2018, 3, 28, 14, 16, 39, 107306)

format (now, "%h:%m:%s")
out[11]: ' 14:16:39 '
format (now, "%y-%m-%d")
out[15]: ' 2018-16-28 '

If the format method is not defined in the class, the method inherited from Object returns STR (my_object). So if you want to implement the effect of formatting words in a custom class, you need to use the rewrite format method to control the display

However, if the format specifier is passed in, object. The format method throws TypeError:

>>> format (v1, '. 3f ')
Traceback (most recent call last):

typeerror:non-empty format string passed to obj ect.__format__
9.6 Two-dimensional vector with hash

Implementing the vector2d of the hash, by definition The current VECTOR2D example is not hashed, and therefore cannot be directly placed into the collection \

If you need to implement a hash type, you need to implement the __hash__ and __eq__ methods, the sample hash value should never change, so when you need to use the attribute, you need to ensure that the property is read-only

__int__ and __float__ can be called separately by int () and float () to facilitate type conversions that are enforced in some cases. 9.7 Python's private properties and "use of protected properties "

Python uses the __mood form when it implements private properties. Two leading underscores, trailing without or at most one stroke
To name an instance property, Python stores the attribute name in the __dict__ property of the instance and adds a
Underscore and class name. Therefore, for the Dog class, the __mood will become _dog__mood, and for the Beagle class, it will
Into _beagle__mood. This language feature is called name rewriting

dog.__dict__
{' _dog__name ': ' Haha '}

The Python convention uses a single underline self._name to handle private properties, and the Python interpreter does not make changes to the underscore, so it is not accessible outside of the class. It is easy to follow a private property that uses an underscore object, just as it is most likely to write constants in all uppercase letters. 9.8 Save space using the solts class attribute

By default, Python stores instance properties in a dictionary named dict in each instance. As described in the 3.9.3 section,
In order to use the underlying hash table to elevate the access speed, the dictionary consumes a lot of memory. If you want to process millions of properties without
Multiple instances, by slots class properties, can save a lot of memory by letting the interpreter store the instance in a tuple
property without using a dictionary.

The __slots__ property inherited from the superclass has no effect. Python only uses the __slots__ attribute defined in each class.

The way to define slots is to create a class attribute, use the name of slots , and set its value to
A string of iterated objects in which each element represents each instance property. I like to use tuples because
The information contained in the slots of this definition will not change.

Class vector2d: "" "
    use __solts__ to limit the storage location of properties in a class" ""
    __slots__ = ("__x", "__y")
    TypeCode = ' d '

# if you use __ solts__ to fix the properties of the class, so there will be no more object.__dict__ this built-in attribute, which will deposit the value of the attribute into a similar tuple

The purpose of defining the slots property in a class is to tell the interpreter: "All instance properties in this class are here
Up. "In this way, Python uses a tuple-like structure to store instance variables in each instance to avoid using the elimination
Dict property that consumes memory. If there are millions of instances of simultaneous activity, this can save a lot of

In addition, there is an instance property that may need to be noted, that is, the weakref property, in order for the object to support weak references
(see section 8.6), this property must be available. The weakref attribute is default in a user-defined class. However, as
The Slots attribute is defined in the fruit class, and you want to use the instance as the target of the weak reference, then the 'weakref'
Added to the slots .

In summary, some of theslots attributes need to be noted, and can not be abused, can not use it to restrict the user can assign value
's Properties. Slots properties are most useful when working with list data, such as schema-invariant database records, and oversize datasets. However, if you often work with large amounts of data, be sure to understand NumPy

Slots Problems
In summary, if used properly, slots can significantly save memory, but there are a few points to note.
• Each subclass defines the slots property because the interpreter ignores the inherited slots property.
• Instances can only have properties listed in slots unless the ' dict ' is added to slots (Do this
Lost the memory-saving effect).
• An instance cannot be the target of a weak reference unless the ' weakref ' is added slots .
If your program does not have to deal with millions of instances and may not be worth the effort to create an unusual class, disable it to create dynamic properties or do not support weak references. As with other optimizations, you should use the slots Properties

Only if you weigh the current requirements and carefully collect the
material to prove that it really is necessary.

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.