search
HomeDatabaseMysql Tutorialpython descriptor descriptor(1)

Python descriptors are a way to create managed properties. Whenever an attribute is queried, an action occurs. This action defaults to get, set or delete. However, sometimes an application may have more requirements and require you to design more complex actions. The best solution is to write a function that performs the desired action, and then specify that it runs when the property is accessed. An object

with this functionality is called a descriptor. Descriptors are the basis for the implementation of Python methods, bound methods, super, PRperty, staticmethod and classmethod.

1. Descriptor protocol

A descriptor is an object that represents an attribute value. By implementing one or more __get__, __set__, __delete__ methods, the descriptor can be linked to the attribute access mechanism, and these can also be customized. operate.

__get__(self, instance, own): used to access attributes and return the value of the attribute. Instance is the instance object using the descriptor, and own is the class to which the instance belongs. When accessing a property through a class, instance is None.

__set__(self,instance,value): Set attribute value.

__delete__(self,instance): Delete attribute value.

2. How to implement descriptors

class Descriptor(object):

def __get__(self, instance, owner):

print 'getting:%s'%self._name
return self._name
def __set__(self, Instance, name):
Print' setting:%s'%name
self._name = name
def __delete __ (self, instance):
Print 'deleting:%s'%seld._name
SS Person (object):
name = Descriptor()


A very simple descriptor object is generated. Now you can read, set and delete the attribute name of a Person object:

>>> p =Person()

>>> p.name='john'

setting:john

>>> p.name
getting:john
'john'
>>> del p. name
deleting:john


Note: Descriptors can only be instantiated at the class level, descriptors cannot be created for each instance by creating descriptor objects in __init__() and other methods.

Property names used by classes with descriptors have higher priority than property names stored on instances. In order for a descriptor to store a value on an instance, the descriptor must pick a name that is different from the name it itself uses.

As in the above example, the name cannot be used when the Person class initialization __init__ function sets attributes for the instance.

data descriptor and none-data descriptor:

If __get__ and __set__ are implemented, it is a data descriptor, if only __get__ is implemented, it is a non-data descriptor. The different effect is that the data descriptor always replaces the attribute implementation in an instance,

and the non-data descriptor does not have a set, when assigning values ​​​​to attributes through the instance, such as the above p.name = 'hello', it does not The __set__ method will be called again, and the instance attribute p.name will be directly set to 'hello'.

Of course, if you only raise AttributeError in __set__, you will still get a non-data descriptor.

Descriptor calling mechanism:

When querying the attribute a.attr of an object, if python finds that attr is a descriptor object, how to read the attribute depends on the object a:

Direct call: The simplest call is to use it directly The code calls the descriptor method, attr.__get__(a)

Instance binding: If a is an instance object, call the method: type(a).__dict__['attr'].__get__(a,type(a))

Class binding: If A is a class object, call the method: A.__dict__['attr'].__get__(None,A)

Super binding: If a is a super instance, then super(B,obj).m () Find B’s base class A by querying obj.__class__.__mro__, and then execute A.__dict__['m'].__get__(obj,obj.__class__)

3. Descriptor that performs attribute type checking

class TypedProperty(object):
def __init__(self,name,attr_type,default=None):
self.name='_'+name
self.type=attr_type
self.default=default if default else attr_type()
def __get__(self,instance,own):
return getattr(instance,self.name,self.default)
def __set__(self,instance,value):
if not isinstance(value,self.type):
raise TypeError,'Must be %s'%self.type
setattr(instance,self.name,value) def __delete__(self,instance):
raise AttributeError('Can not delete attribute')
class Foo(object):
name=TypedProperty('name',str)
num=TypedProperty('num',int,37)


The above descriptor can check the type of the attribute. If the name attribute is not set to str type or num is not If set to int type, an error will be reported:

>>> f.name=21

TypeError: Must be

and deletion of attributes is prohibited:

> >> del f.name

AttributeError: Can not delete attribute

f.name Invisible call type(f).__dict__['name'].__get__(f,Foo), that is, Foo.name.__get__( f,Foo).

The above descriptor is actually stored on the instance. Name is stored on f._name through setattr(f,_name,value), and num is stored on f._num. This is also the reason for underlining,

Otherwise the descriptor The name name will conflict with the instance attribute name, and the descriptor attribute f.name will overwrite the instance attribute f.name.

The above is the content of python descriptor descriptor (1). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

MySQL String Data Types: A Comprehensive GuideMySQL String Data Types: A Comprehensive GuideMay 08, 2025 am 12:14 AM

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,idealforconsistentlengthdatalikecountrycodes;2)VARCHARforvariable-lengthstrings,suitableforfieldslikenames;3)TEXTtypesforlargertext,goodforblogpostsbutcanimpactperformance;4)BINARYandVARB

Mastering MySQL BLOBs: A Step-by-Step TutorialMastering MySQL BLOBs: A Step-by-Step TutorialMay 08, 2025 am 12:01 AM

TomasterMySQLBLOBs,followthesesteps:1)ChoosetheappropriateBLOBtype(TINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB)basedondatasize.2)InsertdatausingLOAD_FILEforefficiency.3)Storefilereferencesinsteadoffilestoimproveperformance.4)UseDUMPFILEtoretrieveandsaveBLOBsco

BLOB Data Type in MySQL: A Detailed Overview for DevelopersBLOB Data Type in MySQL: A Detailed Overview for DevelopersMay 07, 2025 pm 05:41 PM

BlobdatatypesinmysqlareusedforvoringLargebinarydatalikeImagesoraudio.1) Useblobtypes (tinyblobtolongblob) Basedondatasizeneeds. 2) Storeblobsin Perplate Petooptimize Performance.3) ConsidersxterNal Storage Forel Blob Romana DatabasesizerIndimprovebackupupe

How to Add Users to MySQL from the Command LineHow to Add Users to MySQL from the Command LineMay 07, 2025 pm 05:01 PM

ToadduserstoMySQLfromthecommandline,loginasroot,thenuseCREATEUSER'username'@'host'IDENTIFIEDBY'password';tocreateanewuser.GrantpermissionswithGRANTALLPRIVILEGESONdatabase.*TO'username'@'host';anduseFLUSHPRIVILEGES;toapplychanges.Alwaysusestrongpasswo

What Are the Different String Data Types in MySQL? A Detailed OverviewWhat Are the Different String Data Types in MySQL? A Detailed OverviewMay 07, 2025 pm 03:33 PM

MySQLofferseightstringdatatypes:CHAR,VARCHAR,BINARY,VARBINARY,BLOB,TEXT,ENUM,andSET.1)CHARisfixed-length,idealforconsistentdatalikecountrycodes.2)VARCHARisvariable-length,efficientforvaryingdatalikenames.3)BINARYandVARBINARYstorebinarydata,similartoC

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.