Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use getattr,__getattr__,__getattribute__ and _ _ get__ in Python

Shulou Source: shulou.com Published: 2022-06-02 05:14:36 09月22日 Update

This article will explain in detail how to use getattr,__getattr__,__getattribute__ and _ _ get__ in Python. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Getattr

Getattr (object, name [, default]) is one of the built-in functions of Python, which is used to get the properties of an object.

Example

> class Foo:... Def _ _ init__ (self, x):... Self.x = x... > > f = Foo (10) > getattr (f,'x') 10 > f.x10 > getattr (f, 'yearly,' bar') 'bar'__getattr__

Object.__getattr__ (self, name) is an object method that is called when the property of the object is not found.

Example

> class Frob:... Def _ _ init__ (self, bamf):... Self.bamf = bamf... Def _ _ getattr__ (self, name):... Return 'Frob does not have `{}` attribute.'.format (str (name))... > > f = Frob ("bamf") > f.bar'Frob does not have `bar` attribute.' > f.bamf'bamf'getattribute

Object.__getattribute__ (self, name) is an object method that is called unconditionally when accessing the properties of an object. This method should return a property value or throw an AttributeError exception.

Example

Class Frob (object):... Def _ _ getattribute__ (self, name):... Print "getting `{}`" .format (str (name)).. Return object.__getattribute__ (self, name)... > > f = Frob () > > f.bamf = 10 > f.bamfgetting `bamf`10get

The _ _ get__ () method is one of the descriptor methods. The descriptor is used to transform access object properties into calling descriptor methods.

Example

Class Descriptor (object):... Def _ _ get__ (self, obj, objtype):... Print ("get value= {}" .format (self.val)). Return self.val... Def _ _ set__ (self, obj, val):... Print ("set value= {}" .format (val)). Self.val = val... > > class Student (object):... Age = Descriptor (). > > s = Student () > > s.age = 12set value=12 > print (s.age) get value=1212 on "how to use getattr,__getattr__,__getattribute__ and _ _ get__ in Python" is here. I hope the above content can be of some help to you, so that you can learn more knowledge. If you think the article is good, please share it out for more people to see.

Tags: Methods objects properties examples articles more good practical useful content functions articles knowledge references help about Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info macOS Apple Redmi Xiaomi