In the following article we will look at what is
custom classes in Python。 Find out what is
Python custom class, and what the Python custom class can do in Python programming.
It is important to note that a variable or function name such as __xxx__ is similar to __slots__, which has a special purpose in Python.
__slots__ we already know how to use it, the __len__ () method We also know is to allow class to act on the Len () function.
In addition, there are many special purpose functions in Python's class that can help us customize the class .
__str__
Let's first define a student class and print an instance:
>>> class Student (object): ... def __init__ (self, name): ... Self.name = name...>>> Print (Student (' Michael ')) <__main__. Student Object at 0x109afb190>
Print out a bunch of <__main__. Student object at 0x109afb190> it looks rather unattractive.
How can you print it well? Just define the __str__ () method and return a good-looking string:
>>> class Student (object): ... def __init__ (self, name): ... Self.name = Name ... def __str__ (self): ... Return ' Student object (name:%s) '% self.name...>>> print (Student (' Michael ')) Student object (Name:michael)
This kind of printed example, not only good-looking, but also easy to see the important data inside the instance.
But careful friends will find the direct knocking variable without print, the printed instance is not good to see:
>>> s = Student (' Michael ') >>> s<__main__. Student Object at 0x109afb310>
This is because the direct display of the variable calls is not __str__ (), but __repr__ (), the difference between the two is __str__ () returns the string that the user sees, and __repr__ () returns the string that the program developer sees, that is, __repr__ () is for debugging services.
The solution is to define a __repr__ () again. But usually the __str__ () and __repr__ () codes are the same, so there's a lazy way to do it:
Class Student (object): def __init__ (self, name): self.name = name def __str__ (self): return ' Student Object (name=%s) '% self.name __repr__ = __str__