When to use Python special methods?
I know that classes can implement var开发者_StackOverflow社区ious special methods, such as __iter__
, __setitem__
, __len__
, __setattr__
, and many others. But when should I use them? Can anyone describe typical scenarios when I would want to implement them and they would simplify programming in Python?
Thanks, Boda Cydo.
I think you basically answered your question.
Become familiar with the special methods. If you find that using one will make your program simpler, use it. If you don't understand what one is for, or feel like it is a more complex solution - you have answered the question. Don't use it.
The typical scenarios are :
Overriding operators
Catching access to attributes that don't exist and dealing with that access (
__getattr__
)Manipulating class and instance creation (
__init__
,__slots__
,__new__
)Customizing string representations (
__str__
and__repr__
)allowing callability (
__call__
)Hooking into convenient/well-used builtin syntax (
__getitem__
,__len__
, etc...)
These are mostly covered at https://docs.python.org/reference/datamodel.html#specialnames and http://docs.python.org/reference/datamodel.html#special-method-names
Well, the short answer is: when you need them.
Since there are a lot of built in functions I can't answer for all of them. However, you can almost all the time manage without ever overriding a builtin Python function.
Usually when you do need them is when you'd like your object to behave like a builtin datatype in Python. For example if you'd like to be able to run
len(...)
on your object (override _____len_____(...)), or compare two objects of your datatypes like so:
obj1 < obj2
(override _____cmp_____(...)) to do this.
If you're creating a class that should act sort of like an array or dictionary, these are very useful so that your syntax looks familiar. For example, if you wanted to create an ordered dictionary, you could use all of the functions you mentioned so that you could interchange that with a regular dictionary.
getattr
and setattr
are useful when you want to implement an interface by delegating to an instance member instead of straight inheritance. You map them to the getattr
and setattr
of the member.
精彩评论