1. __str__ and repr in Python
If you want to turn an instance of a class into STR, you need to implement a special Method __str__ ():
class Person (object): def __init__ (self, Name, gender): = name = gender def__str__(self): return '(person:%s,%s)' % (Self.name, Self.gender)
Now try print on the interactive command line:
>>> p = person ('Bob''male')print p (person:bob, male)
However, if you hit the variable p directly:
>>> P<main. Person object at 0x10c941890>
It seems that __str__ () will not be called.
Because Python defines both __str__ () and __repr__ () methods, __str__ () is used to display to the user, and __repr__ () is used to display to the developer __repr__()
for debugging services.
There's a lazy way to define __REPR__:
class Person (object): def __init__ (self, Name, gender): = name = gender def__str__(self): return '(person:%s,%s)' % (self.name, Self.gender) __repr__ __str__
Instance:
classPerson (object):def __init__(self, Name, gender): Self.name=name Self.gender=GenderclassStudent (person):def __init__(self, name, gender, score): Super (Student, self).__init__(name, gender) Self.score=scoredef __str__(self):return '(student:%s,%s,%d)'%(Self.name,self.gender,self.score) s= Student ('Bob','male', 88)Print(s)
2. __cmp__ in Python
When sorting built-in data types such as int, str, Python's sorted () is sorted by the default comparison function CMP, but if you sort an instance of a group of Student classes, you must provide our own special Method __cmp__ ():
classStudent (object):def __init__(self, Name, score): Self.name=name Self.score=scoredef __str__(self):return '(%s:%s)'%(Self.name, Self.score)__repr__=__str__ def __cmp__(self, s):ifSelf.name <S.name:return-1elifSelf.name >S.name:return1Else: return0
The Student class implements the __cmp__ () method, and __cmp__ compares it with the instance self and the incoming instance s, and returns 1 if it should be in front, and returns 1 if the s should be in front, and returns 0 if both are equal.
The student class implements sorting by name:
>>> L = [Student ('Tim'), Student ('Bob', 88), Student ('Alice', +)]print, (bob:88), (tim:99) ]
Note: If the list contains more than just the Student class, __cmp__ may get an error:
3. __len__ in Python
If a class behaves like a list, the Len () function is needed to get the number of elements.
For the Len () function to work properly, the class must provide a special method, __len__ (), which returns the number of elements.
For example, we write a Students class that passes the name in:
class Students (object): def __init__ (Self, *args): = args def__len__(self): return len (self.names)
As long as the __len__ () method is implemented correctly, the Len () function can be used to return the "length" of the students instance:
>>> ss = Students ('Bob'Alice'Tim ')print len (ss)3
4. Mathematical operations in Python
The basic data types provided by Python int, float can do integer and floating point arithmetic, and the exponentiation operation.
However, arithmetic is not limited to int and float, it can also be rational number, matrix, etc.
To represent a rational number, you can use a rational class to represent:
class Rational (object): def __init__ (self, p, q): = p = q
P and q are integers, which represent rational number p/q.
If you want rational to perform a + operation, you need to implement __add__ correctly:
classRational (object):def __init__(self, p, q): SELF.P=P SELF.Q=Qdef __add__(self, R):returnRational (SELF.P * r.q + self.q * R.P, SELF.Q *r.q)def __str__(self):return '%s/%s'%(SELF.P, SELF.Q)__repr__=__str__
Now you can try the rational number addition:
>>> r1 = Rational (1, 3)>>> r2 = rational (1, 2)print r1 + R25/6
5. type conversion in Python
The rational class implements the rational number operation, but what if you want to convert the result to int or float?
To examine the conversion of integers and floating-point numbers:
>>> Int (12.34)12>>> float (12.0)
If you want to convert Rational to int, you should use:
r = Rational (5= Int (r)
for the Int () function to work correctly, you only need to implement a special Method __int__ ():
class Rational (object): def __init__ (self, p, q): = p = q def__int__(self): return SELF.P//SELF.Q
The results are as follows:
print int (rational (7, 2))print int (rational (1, 3)) 0
Similarly, for the float () function to work properly, you only need to implement a special Method __float__ ().
Custom classes in Python