官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 武山县| 方城县| 什邡市| 宁波市| 广饶县| 洪雅县| 瑞丽市| 长武县| 镇宁| 仁化县| 富平县| 雅安市| 广丰县| 建阳市| 高碑店市| 枣强县| 贵阳市| 信阳市| 清苑县| 湘乡市| 定州市| 砚山县| 临泉县| 客服| 房产| 军事| 方城县| 迁安市| 鹤壁市| 沐川县| 红桥区| 巢湖市| 屯昌县| 陵川县| 德保县| 泸水县| 巍山| 辽中县| 揭东县| 宾川县| 华安县|