Fish C Notes--python Magic Method Three: Property access __python

Source: Internet
Author: User

__getattr__ (self, name) defines the behavior when a user attempts to get a nonexistent attribute: When the object's time Name property is accessed, __getattr__ is automatically invoked if the Name property does not exist. If present, the __getattr__ method is not invoked, but the Name property is returned directly

__getatribute__ (self, name) defines the behavior when the property of the class is accessed when the object's Name property is accessed, and the method is called whenever the name is not present

__setattr__ (self, name, value) defines the behavior of a property when it is set when an attempt is made to assign a value to an object's Name property.

__delattr__ (self, name) defines the behavior of an object when it is deleted


All four of these methods are available in addition to __getattr__ (object.) Way to query for help, but __getattr__ how to query is not quite known

By rewriting these four magic methods, we can control the access to the object's properties.


Three of these methods and the front of the GetAttr, SetAttr, delattr is different, one by two strokes, one did not (Leng a few minutes before the reaction came, embarrassed)

See above: http://blog.csdn.net/sinat_41104353/article/details/79250415

>>> class C:
	def __getattribute__ (self, name):
		print ("GetAttribute") return
		Super (). __ GETATTRBUTE__ (name)        #为了不影响原来__getattribute__功能的使用, it calls the base class's __getattribute__
	def __getattr__ (self, name):
		print ("GetAttr")                           #这里调用super (). __GETATTR__ (name) will error: Attributeerror: ' Super ' object has no attribute ' __ Getattr__ '
	def __setattr__ (self, Name, value):
		print ("SetAttr")
		super (). __SETATTR__ (name, value)
	def __delattr__ (self, name):
		print ("Delattr")
		super (). __DELATTR__ (name)

		
>>> C = C ()
>>> c.x         #创建一个属性x
getattribute    #首先会调用__getattribue__方法
getattr

>>> c.x = 1
setattr

>>> c.x
getattribute
1               #理论上应该是1, but I don't know why I always try getattr

> >> del c.x
delattr


Note: Rewriting these methods can easily cause a dead loop


Look at the following example:

Write a rectangular class with a long and wide two properties by default

If you assign a value to a property called Square, then this is a square, and the value is the length of the square, and the length and width should equal the length of the edge. If the property is not assigned a value for another name, the property is assigned a value.

>>> class Rectangle:def __init__ (self, width = 0, height = 0): Self.width = width #发生赋值操作, it triggers __ setattr__ Method self.height = height def __setattr__ (self, Name, value): if name = = ' Square ': self.width = value SE Lf.height = value Else:self.name = value #又是一个赋值操作, triggering the __setatrr__ method, resulting in a dead loop resolution (1) This is changed to the __setattr__ method of calling the base class, that is, super ( ). __setattr__ (name, value), generally recommended this one (2) changed to self.__dict__[name] = value def getarea (self): return self.width * Self.heigh T >>> r = Rectangle (4, 5) #传入参数调用__init__方法 Traceback (most recent call last): File "
    <pyshell#55> ", line 1, in <module> r = Rectangle (4, 5) File" <pyshell#54> ", line 3, in __init__ Self.width = width File "<pyshell#54>", line ten, in __setattr__ self.name = value file <pyshell#54> ", line, in __setattr__ self.name = value File ' <pyshell#54> ', line ten, in __setattr__ self.name = Valu e [Previous Line RepeaTed 325 more times] File "<pyshell#54>", line 6, in __setattr__ if name = = ' Square ': Recursionerror:maximum R Ecursion depth exceeded in comparison

>>> r = Rectangle (4, 5)
>>> R.getarea ()

>>> r.square =
>>> R.width
>>> r.height
>>> r.getarea ()
100

Of course, not only is there a __setattr__ method that causes a dead loop, __getattribute__ also avoids the method of seeing code annotations.


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.