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

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:

主站蜘蛛池模板: 南木林县| 吴忠市| 定西市| 广灵县| 安远县| 江孜县| 固原市| 县级市| 英德市| 广安市| 通山县| 赞皇县| 叙永县| 锡林郭勒盟| 射阳县| 合作市| 榕江县| 余江县| 永丰县| 剑川县| 绥化市| 错那县| 吐鲁番市| 靖江市| 兖州市| 布拖县| 金塔县| 古丈县| 天柱县| 贵德县| 体育| 六枝特区| 石嘴山市| 翼城县| 长丰县| 乌拉特前旗| 朝阳市| 文成县| 吉林省| 积石山| 得荣县|