class Student(object): # class Class name ( Inherit )
pass
init() The way is java The constructor in
Class self amount to java Medium this,java Don't show declaration ,python You need to declare in the parameter list
The first parameter must be self
Access restrictions
Private attributes are double underlined __ start , Only internally accessible (private)
Access needs to be provided by the class get Method , This sum java equally _ Modification is required set Method
actually , It's not private , It's just python The interpreter changed the name of the attribute , Turn into ._ Class name __ Property name
python The beginning and end of a double underscore , Are special variables , Generally, you can't use
Find a fun , Even if there are no attributes in the class , It can be xx.xx = xx Set up , Then you can use it
Inherit
Inheritance causes polymorphism
A child is a parent , The parent class is not a child class
The caller just calls , No matter the details , There is no need to know the subtype , So as to meet the opening and closing principle as much as possible
java It's a static language , It checks whether the type of the incoming object is legal when compiling
Python It's dynamic language , There is no need to guarantee that the type is complete , As long as it has the methods and attributes required in this method ok 了
The duck type , No strict inheritance , as long as Looks like a duck , I walk like a duck Just ok
Object information
type(obj) type , Pointing function
type(obj)
if type(xxx) == type( Known types )
if type(xxx) == types.FunctionType Determine if it's a function …
instance(obj, Known types ) Judge whether the types are equal
return True or False
Available for inheritance
Judge whether it is one of them instance(obj,(xxx,xxx))
dir(obj) Will all methods attribute String list returns
len(obj) Get the length of the object
Automatically call __len__() Method
Can be copied
hasattr(obj,“xxx”) Whether it has some attribute
Notice the string
getattr(obj,“xxx”,404) The last parameter is the default value , Prevent error reporting
Methods and properties are the same , All use this
setattr(obj,“xxx”,xx)
Combine the above duck types , You can use object information to determine whether it looks like a duck
if hasattr(obj,“xxx”): …
Instance properties and class properties
Instances can be bound to any property
Class has no definition name attribute , But I can example .name=xxx, And then use
slots
As a dynamic language ,python You can bind methods and properties to instances
And dynamically bind classes , Can be applied to every instance , The specific operation is the same as the instance binding
To limit binding , need __slots__
As a variable , Can define Allow binding The attribute name
Other properties cannot be bound
Invalid for inherited subclasses
@property
General attributes are not exposed to the public , So we need to getter Method ,setter Method
This is very troublesome to use
So you can actually use @property To make the get Methods become properties , And then use @ attribute .setter annotation setter Method
class Stu(Object):
@property
def score(self): # Under this annotation is the attribute name
return self.__score
@score.setter
def score(self,val):
self.__score = val
At this point, you can directly xx. attribute Assign and call , Do not write get Assigned a value to , A lot of convenient
xx = Stu()
xx.score = css
print(xx.score)
The principle is decorator
Be careful The method name of the property should not be the same as Actual attribute name identical
If the same , It's going to happen Self ring , This leads to infinite recursion , Final stack overflow
Pay attention to any method here , All names should be unified , That's you Annotation defines score, Then all the methods have to be called score
multiple inheritance
When multiple categories intersect , Will cause The hierarchy of classes is complex
This is different from java,java It's single inheritance , Then use the interface to extend
class Bat(Mammal,FlyableMixIn,XxxMinIn):
pass
Inherit the functions of multiple parent classes at the same time
We can call the first inherited class mainline , Other extra classes mixed in , be called MixIn
Custom class
str() Print instance information , direct print that will do , Customizable
repr() Print instance information , For debugging service
iter() Implement the method , Pre knowledge of list generation , This class can be used for for…in, To become a Iterable object
Generally, it should be matched with a __next__() The method is to
getitem() You can think of a class as list To use , Click below to access the element
getattr() When an attribute cannot be found ,python The interpreter will call this method
call(), Use the instance object as a method xxx() Think of objects as functions
Enumeration class
from enum import Enum
@unique # Check for duplicate values
class Weekday(Enum):
Sun = 0
Mon = 1
...
print(Weekday.Mon) # 1
The metaclass
from hello import Hello
h = Hello()
h.hello()
among ,Hello It's a class, Its type is type
h yes Hello Example , Its type is Hello
type() You can return the type of an instance : type(obj)
type() You can also create new types , There is no need to class Hello(object) And so on
type(class name , Collection of parent classes of base inheritance (tuple,), Method name )
def function(self): # there self There must be , Because we need to create classes
print("ok")
Hello = type("Hello",(object,),dict(hello=function))
h = Hello()
h.hello()
metaclass The metaclass
For classes , First we define the class , Then create an instance
metacalss Is the meta of a class , First define metaclass, Then create the class , Then create an instance