- 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:

- PHP 從入門到項目實踐(超值版)
- Scratch 3.0少兒編程與邏輯思維訓練
- 名師講壇:Java微服務架構實戰(SpringBoot+SpringCloud+Docker+RabbitMQ)
- 青少年Python編程入門
- INSTANT Passbook App Development for iOS How-to
- Active Directory with PowerShell
- RSpec Essentials
- Mastering Business Intelligence with MicroStrategy
- Mastering React
- 微信小程序開發與實戰(微課版)
- Internet of Things with ESP8266
- Raspberry Pi Robotic Blueprints
- 嵌入式Linux C語言程序設計基礎教程
- Java Hibernate Cookbook
- SQL Server實例教程(2008版)