1. What if we want to restrict the properties of an instance? For example, only add and attributes to student instances are allowed name
age
.
For the purpose of limiting, Python allows you to define a special variable when defining a class __slots__
to limit the attributes that the class instance can add:
2, use __slots__
to note that the __slots__
defined properties only work for the current class instance, and it does not work for inherited subclasses.
3, in order to limit the scope of score, you can use a set_score()
method to set the score, and then through a get_score()
to get results, so that in the set_score()
method, you can check the parameters
4. Because Python allows multiple inheritance, mixin is a common design.
Only single-inherited languages, such as Java, are allowed to use the mixin design.
5.
This is because the direct display of variable calls is not __str__()
, but the __repr__()
difference between the two is to return the string that the __str__()
user sees, and the __repr__()
string that the program developer sees, that __repr__()
is, for debugging services.
The solution is to define one more __repr__()
. But it's usually __str__()
__repr__()
the same as the code, so there's a lazy way to do it:
1>>>classStudent (object):2 def __init__(self,name):3Self.name =name4 def __str__(self):5 return"Student Object (name:%s)"%Self.name6 __repr__=__str__7 8 9>>> S=student ('Mike')Ten>>>s OneStudent Object (name:mike)
Liaoche Python excerpt 7