The setttr () function sets the attribute of the specified object by its name.
This is a GETATTR () function analogue. The arguments are Object, a line with the name of NAME Attribute and the arbitrary value of Value of the installed attribute.
The name NAME should be the name of the existing attribute or a new attribute will be created. The function will assign a value to the attribute if the object allows this. For example Setattr (X, 'Foobar', 123), equivalent to X.foobar = 123
-For the return of the attribute, getttr () is used.
-For removal of the attribute, DELATTR () is used.
-For checking the existence of the attribute, Hasattr () is used.
π access to attributes
The attributes of the object in Python are the named fields (data, functions) inherent in this object (copy, class).
The easiest access to attributes is through a point:
If we turn to the attribute that is not, we will get the Attributeerror error. We can reduce this behavior by implementing the magic methods __Getttr__ or __Gettribute__.
__getttr__ is called if the attribute is not found in the usual way (was not specified earlier through the point, the setttr function, or through __dict__). If the attribute is found, then __getttr__ is not called.
π Example. We return -1 for any non -existent attribute.
The __Gettribute__ method is called when we are trying to get any attribute, regardless of whether it is or not. This method is called before __getttr__. He's a little more cunning. If __Gettribute__ throws Attributeerror, it will be caused by __getttr__.
π Example. We can prohibit reading some attributes:
⚠️ Attention! In __Gettribute__, we can call Super () .__ getttribute __ (item) or Object .__ gettribute __ (Self, Item), but does not serve the RETURN SELF .__ [ITEM] or RETURN SETITRIBITRA (self, item), as this will lead to endless recursion.
π‘ There is also a magic method __setttr __ (Self, Key, Value), called by Obj.key = Value or Setttr (Obj, 'Key', Value). He does not have a longer twin brother.
To complete the picture, there is still a built -in Getattr function (Object, Name [, Default]). Getettr call (x, 'y') is similar to circulation through the point: X.Y in the first case 'Y' - this is a line, which allows us to dynamically receive attributes of objects, in contrast to a point that requires a fixed name at the stage of writing code. In the event that the attribute is not available, we get attributeerror with an unnecessary Default or get Default (without error) if Default was set by the third argument.
#machinelearning #artificialintelligence #ai #datascience #Programming #Technology #DEEPLEARNING