1. Create a class
1 class Book (object): 2 def __init__ (self,b): #定义构造器 3 self.name=b4 print Self.name5 def UpdateName (self,a):6 self.name= A7 print self.name
Attention:
- __init__ () is called (implicitly called) when instantiated.
- The self parameter is automatically passed by the interpreter.
2. Creating an instance (instantiation of the Class)
1 c=book ('Mike')
Attention:
- When creating an instance of a class, pay attention to the number of arguments. For example, the self is passed automatically, and only a parameter of B is required.
3. Accessing class instance properties and method calls
1 >>> c.name2'Mike'3 >>> C.updatename ('jone')4jone5 >>> C.name 6 ' Jone '
4. Creating subclasses
1 class Allbook (book): 2 def __init__ (self,b,em): 3 Book. __init__ (self,b) 4 self.email=em5 def Updateemail (self,d):6 self.email=D7 print self.email
Attention:
- Subclasses inherit the properties of the base class.
- In the above example, the subclass overrides the constructor of the base class (__init__ ()), the constructor of the base class is not automatically called, so the subclass is best to define its own constructor, otherwise the constructor of the base class is called.
1>>> E=allbook ('Mike','[email protected]')2 Mike3>>>E.email4 '[email protected]'5>>> E.updateemail ('[email protected]')6666@qq. com7>>>E.email8 '[email protected]'
Basics of Python classes