"Python" "python-object.py"

Source: Internet
Author: User
Tags bitwise operators

"""
From array Import array
Print (bytes ([9])) #当source参数是一个可迭代对象, the elements of this iteration object must conform to 0 <= x < 256 so that they can be initialized into the array
Print (bytes (Array (' d ', ())))
‘‘‘
First introduce
From array Import array
The list is then passed directly to the array parameter into the constructor. (I don't know if it's called a constructor)
Np.array (' d ', [+])
Turn back then call the ToList function
_.tolist ()
‘‘‘

#例子9-4 comparison of Classmethod and Staticmethod
Class Demo:
@classmethod
def klassmeth (*args):
return args
@staticmethod
def statmeth (*args): #行为和普通函数相似
return args
Print (Demo.klassmeth ()) # (<class ' __main__. Demo ';,)
Print (Demo.klassmeth (' spam ')) # (<class ' __main__. Demo ';, ' spam ')
Print (Demo.statmeth ()) # ()
Print (Demo.statmeth (' spam ')) # (' Spam ',)

"""
#9.2 further talk about vector classes
#例子9-2 defines a special method
Import Array
Import Math
Class Vector2d:
TypeCode = ' d '
‘‘‘
def __init__ (self,x,y):
self.x = float (x) #转换称浮点数 to catch errors early in case the VECTOR2D function is called when improper arguments are passed in
Self.y = float (y)
‘‘‘
def __iter__ (self):
Return (I for I in (SELF.X,SELF.Y)) #把Vector2d实例变成可迭代对象 so that the package can be disassembled (for example, x, y = my_vector).
def __repr__ (self):
Class_name = Type (self). __name__
Return ' {} ({!s},{!s}) '. Format (class_name,*self) #因为Vector2d实例是可迭代对象, so **self will provide the X and Y components
def __str__ (self):
Return str (tuple (self)) #用可迭代实例可生成元祖
def __bytes__ (self): #python有个独特的特性: Class properties can be used to provide default values for instance properties. Although the instance has no attribute typecode at this point, it is now defaulted from Vector2d.typecode
#但是. If you assign a value to an instance property that does not exist, the instance property is created. If we assign a value to the TypeCode instance property, then the class property of the same name is not affected. However, since then, the instance read Self.typecode is an instance property, which is
#把同名类属性覆盖了 (but by accessing this property through the class, the value remains the same). With this feature, you can customize different values for the TypeCode properties of each instance
Return (bytes ([Ord (Self.typecode)]) + bytes (Array.array (self.typecode,self))) #为了生成自己序列, we typecode convert the byte sequence, Then iterate over the vector2d instance, get an array, and then convert the array to the byte sequence
@classmethod
def frombytes (cls,octets):
TypeCode = Chr (Octets[0])
MEMV = Memoryview (octets[1:]). CAST (TypeCode)
Return CLS (*MEMV)
def __eq__ (self, Other):
return tuple (self) = = Tuple (Other)
def __abs__ (self):
Return Math.hypot (SELF.X,SELF.Y) #为了比较所有分量, building the progenitor. This can be done for vector2d instances, but there are still problems. With this approach, two more operands are available as vector2d instances, but that vector2d instance and other
#具有相同数值的可迭代对象相比, the result is also true (such as vector2d (3,4) = = [3,4]). This behavior can be seen as a feature and as a defect. Further discussion of operator overloading is possible later
def __bool__ (self):
return BOOL (ABS (self))

def angle (self): #计算角度
Return Math.atan2 (SELF.X,SELF.Y)

def __format__ (self, format_spec= "): #自定义格式代码: If the format description is brushed to the end of ' P ', then the vector is displayed in polar coordinates, i.e. <r,x&gt, where r is modulo, X is radians
If Format_spec.endswith (' P '):
Format_spec = Format_spec[:-1]
coords = (ABS (self), self.angle ())
outer_fmt = ' <{},{}> '
Else
coords = Self
Outer_fmt = ' ({},{}) '
components = (format (C,FORMAT_SPEC) for C in coords)
Return Outer_fmt.format (*components)

#可散列的: The property must be constant, so set the two properties of the instance to read-only, because now we can also assign a value to the property by v1.x. "Step" 1?? #修改构造方法2?? #还要设置 @property3?? Implement the __hash__ method (only immutable vectors can implement this method)
#这个方法应该返回一个整数, it is also desirable to consider the hash value of an object property (the __eq__ method is also used), because an equal object should have the same hash value.
#根据官方文旦, it is best to use bitwise operators to vary or mix the hash values of each component

def __init__ (self,x,y):
self.__x = float (x)
Self.__y = float (y)

@property
def x (self): #这样就可以通过self. x to read it as a public property
Return self.__x
@property
Def y (self):
Return self.__y

def __hash__ (self):
return hash (self.x) ^hash (SELF.Y) #这里可以直接用self. x instead of self.__x because the Read method is set with @property, so the other way is to read the public properties


"""
V1 = vector2d (3,4)
Print (V1.X,V1.Y) #3.0 4.0. The instance component can be accessed directly through the property (without calling the Read value method)
X, y = v1
Print (x, y) #3.0 4.0. Instances can be split into variable-element ancestors
Print (v1) # (3.0, 4.0). The print function calls the STR function
V1 #在控制台, this will print out: vector2d (3.0,4.0)
V1_clone = eval (repr (v1)) #这里用eval函数, indicating that the REPR function calls the vector2d instance to get an accurate representation of the construction method
Print (V1_clone = = v1) #True
Print (ABS (v1)) #5.0
Print (bool (v1), bool (vector2d (0,0))) #True False
octets = bytes (v1)
Print (octets) #b ' d\x00\x00\x00\x00\x00\x00\[email protected]\x00\x00\x00\x00\x00\x00\[email protected] '
#print (Vector2d.frombytes (R ' d\x00\x00\x00\x00\x00\x00\[email protected]\x00\x00\x00\x00\x00\x00\[email protected ]) #这种方式来验证总报错, I can't think of a good verification method for the time being.
#验证格式化
Print (Format (vector2d (), ' P ')) #<1.4142135623730951,0.7853981633974483>
Print (Format (vector2d (), '. 3ep ')) #<1.414e+00,7.854e-01>
Print (Format (vector2d, ' 0.5FP ')) #<1.41421,0.78540>

#验证散列性
V3 = vector2d (3,4)
V4 = vector2d (3.1,4.2)
V5 = vector2d (3,4)
Print (hash (v3), hash (v4)) #7 384307168202284039
Print (hash (v3), hash (v5)) #7 7
Print (V3 = = v5) #True

#9.7 Private properties and "protected" properties
V6 = vector2d (3,4)
Print (v6.__dict__)
Print (v6._vector2d__x)
v6._vector2d__x = 5.0
Print (v6.__dict__)
#这样看来, too dangerous, and some people don't like this syntax, so there are protected properties, although the Python interpreter does not use a single underline attributes to do special processing, but many Python programmers strictly abide by this Convention, Do not access a single underline protected property (Convention which is private) outside of the class

#9.8 Use the __slots__ class attribute to save space: only when you need to deal with big data can you show value, and under normal circumstances don't be so troublesome to create this unusual class.
#默认情况下, Python stores instance properties in a dictionary named __dict__ in each instance. Dictionaries consume a lot of memory in order to increase access speed using a lower-level hash table. This can save a lot of memory if you are dealing with instances with a few properties outside of hundreds of, by having the interpreter store instance properties in Yongzu without using a dictionary
#子类不继承, only the current class is valid
Class V:
__slots__ = (' __x ', ' __y ')
#不过, there's something to watch out for.
#1?? Each subclass defines the __slots__ property, because the interpreter ignores the inherited
#2?? The instance can only have properties listed in __slots__ unless the ' __dict__ ' is added to the __slots__, but doing so loses the memory-saving effect
#3?? If you do not add __weakref__ to __slots__, the instance cannot be the target of a weak reference.

#9.9 Overriding class properties
#例子9-13 Set the TypeCode property inherited from the class to customize an instance property
V7 = vector2d (1.1,2.2)
dumpd = bytes (V7)
Print (DUMPD)
Print (len (DUMPD))
V7.typecode = ' F '
Dumpf = bytes (V7)
Print (DUMPF)
Print (len (Dumpf))
‘‘‘
B ' d\x9a\x99\x99\x99\x99\x99\xf1?\x9a\x99\x99\x99\x99\x99\[email protected] '
17
B ' f\xcd\xcc\x8c?\xcd\xcc\[email protected] '
9
‘‘‘
#例子9 -14 Shortvector2d is a subclass of vector2d and is used only to override the default value of TypeCode
Class Shortvector2d (vector2d):
TypeCode = ' F '
SV = shortvector2d (1/11,1/27)
Print (SV) # (0.09090909090909091, 0.037037037037037035)
Print (len (bytes (SV))) #9
# "Analysis" This also explains why I do not have a hard-coded class_name value in the Vector2d.__repr__ method, but instead uses the type (self). __name__, if hard-coded, then vector2d subclasses will overwrite __repr__ method, just to modify the value of the class_name. From the type of the instance
#读取类名, the __repr__ method can be safely inherited
"""





























































"Python" "python-object.py"

Related Article

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.