- Python Data Structures and Algorithms
- Benjamin Baka
- 293字
- 2021-07-09 19:45:00
Special methods
We can use the dir(object) function to get a list of attributes of a particular object. The methods that begin and end with two underscores are called special methods. Apart from the following exception, special method, are generally called by the Python interpreter rather than the programmer; for example, when we use the + operator, we are actually invoking a call to __add__(). For example, rather than using my_object.__len__() we can use len(my_object) using len() on a string object is actually much faster because it returns the value representing the object's size in memory, rather than making a call to the object's __len__ method. The only special method we actually call in our programs, as common practice, is the __init__ method, to invoke the initializer of the superclass in our own class definitions. It is strongly advised not to use the double underscore syntax for your own objects because of potential current or future conflicts with Python's own special methods.
We may, however, want to implement special methods in custom objects, to give them some of the behavior of built-in types. In the following code, we create a class that implements the __repr__ method. This method creates a string representation of our object that is useful for inspection purposes:
class my_class():
def __init__(self, greet):
self.greet = greet
def __repr__(self):
return 'a custom object (%r)' % (self.greet)
When we create an instance of this object and inspect it, we can see we get our customized string representation. Notice the use of the %r format placeholder to return the standard representation of the object. This is useful and best practice, because, in this case, it shows us that the greet object is a string indicated by the quotation marks:

- 軟件安全技術
- 演進式架構(原書第2版)
- Mastering Concurrency Programming with Java 8
- 微信公眾平臺與小程序開發:從零搭建整套系統
- LabVIEW入門與實戰開發100例
- Rust編程從入門到實戰
- Java 9 Programming Blueprints
- NativeScript for Angular Mobile Development
- 高級C/C++編譯技術(典藏版)
- AppInventor實踐教程:Android智能應用開發前傳
- D3.js By Example
- ExtJS Web應用程序開發指南第2版
- Kotlin Programming By Example
- C++從入門到精通(第6版)
- Python Projects for Kids