Python Object-Oriented Programming learning notes, python Object-Oriented Programming
Class and instance
Classes are associated with instances: classes are definitions of objects, while instances are "real objects". they store the specific information of objects defined in classes.
The following example shows how to create a class:
Class MyNewObjectType (bases): ''' create the MyNewObjectType class ''' class_suite
The keyword is class, followed by a class Name. The following is the class code for defining the class. It usually consists of various definitions and declarations. The biggest difference between a new class and a classic class declaration is that all new classes must inherit at least one parent class, and the parameter bases can be one (single inheritance) or multiple (Multi-inheritance) the parent class used for inheritance.
The process of creating an instance is called Instantiation. The process is as follows (Note: The new Keyword is not used ):
myFirstObject = MyNewObjectType()
The class name uses the familiar function operator () and appears in the form of "function call. Then you usually assign the new instance to a variable. Assignment is not required in syntax, but if you do not save the instance to a variable, it will be useless and will be automatically reclaimed by the garbage collector, because any reference points to this instance. In this way, all you have just done is to allocate a piece of memory for the instance and then release it again.
Classes can be both simple and complex, depending on your needs. In the simplest case, the class is only used as a namespace ). This means that you store data in variables and group them by namespace so that they are in the same link space-the so-called relationship is identified by the standard Python period attribute. For example, if you have a class without any attributes, you can only provide a namespace for the data so that your class has the same features as the structure in C, in other words, such classes share namespaces only as container objects.
Example:
class MyData(object): passmathObj = MyData()mathObj.x = 4mathObj.y = 5mathObj.x + mathObj.y9mathObj.x \\* mathObj.y20
Method
In Python, methods are defined in class definitions, but can only be called by instances. That is to say, the final way to call a method must be as follows: (1) defining classes (and methods); (2) Creating an instance; (3) last step, use this instance to call the method. For example:
Class MyDataWithMethod (object): # define the class def printFoo (self): # define the method print 'you invoked printFoo ()! '
The self parameter exists in all method declarations. This parameter indicates the instance object itself. When you use an instance to call a method, it is passed by the interpreter to the method. Therefore, you do not need to pass self in because it is automatically passed in.
For example, if you have a method with two parameters, you only need to pass the second parameter for all your calls.
The following describes how to instantiate this class and call that method:
> > > myObj = MyDataWithMethod()> > > myObj.printFoo()You invoked printFoo()!
\ _ Init \ () is a special method. In Python, \ init \ () is not actually a constructor. You didn't call "new" to create a new object. (Python does not have the keyword "new" at all ). Instead, after Python creates an instance, it calls the \ init \ _ () method during the instantiation process. When a class is instantiated, additional behaviors can be defined. For example, set the initial value or run some preliminary diagnostic code. It is mainly used to execute some specific tasks or settings after the instance is created and the instance is returned after the instance is instantiated and called.
Create a class (class definition)
Class AddrBookEntry (object): '''address book entry class''' def _ init _ (self, nm, ph): # define the constructor self. name = nm # Set name self. phone = ph # Set phone print 'created instance for: ', self. name def updatePhone (self, newph): # define method self. phone = newph print 'updated phone # for: ', self. name
In the definition of the AddrBookEntry class, two methods are defined: \ _ init \ () and updatePhone (). \ Init \ () is called during instantiation, that is, when AddrBookEntry () is called. You can think that instantiation is an implicit call to \ init \ (), because the parameter passed to AddrBookEntry () is completely consistent with \ init \\_() the received parameters are the same (except self, which is automatically passed ).
Create an instance (instantiate)
>>> John = AddrBookEntry ('John Doe ', '2017-555-1212') # create an instance for John Doe >>> jane = AddrBookEntry ('Jane Doe ', '1970-555-1212 ') # create an instance for Jane Doe
This is the instantiation call, which will automatically call \ _ init \\(). Self automatically passes in the instance object \ init \\_().
In addition, if no default parameter exists, the two parameters passed to \ _ init \ _ () are required during instantiation.
Access instance attributes
> > > john> > > john.name> > > jane.name> > > jane.phone
Once an instance is created, it can be confirmed that our instance attributes are indeed set by \ _ init \ _ () during the instantiation process. We can use the interpreter to "dump" an instance to view what type of object it is.
Method call (through instance)
>>> John. updatePhone ('1970-555-1212 ') # update John Doe's phone number >>> john. phone
The updatePhone () method requires a parameter (excluding self): a new phone number. Check the instance attributes immediately after updatePhone () to verify that the settings have taken effect.
Summary of methods and attributes
Directly add the code, which has been commented out.
# Coding: utf8name = 'yangyanxing 'class Test (): class kevin (): var1 = 'my internal class' name = 'vein' gae = '26' def fun1 (self): print self. name print 'I am a public method' self. _ fun2 () # You can call a private method through the public. During the call, you can change def _ fun2 (self ): print 'I am a private method' @ classmethod def fun3 (self): # You can access this class method through an instance. print' # '* 40 print self. name print 'I am a class method' @ staticmethod # static method. It is also a method that can be accessed without using an instance object. However, you do not need to add self def fun4 () during definition (): print Test. name print name # The name here is the global variable Test. fun3 () print 'I am a static method' print Test. name # public attributes can be directly used without instantiating the object yang = Test () # instantiating a class interyang = Test. kevin () # instantiate an internal class yang. fun1 () # print interyang, a public attribute in the method class. var1 # access the attribute Test in the internal class. fun3 () # Test. fun4 () # coding: utf8class Test (): var1 = 'public attribute of the class' _ var2 = 'private attribute of the class' def fun (self): self. var2 = 'object public attribute' # The Public attribute self of an object is defined here. _ var3 = 'object's private attribute' # The Private Attribute var4 = 'function's local variable' is defined here # The local variable of a function is defined here, here, var4 only uses kevin = Test () # inside the function to instance an object yang = Test () # And another object print kevin. var1 ## print kevin. _ var2 # kevin. fun () print kevin. var2 # There is no var2 before the fun function is called ## print kevin. the private attributes of the _ var3 object cannot be called # print yang. var2 # The var2 in yang still cannot be accessed because the fun method of yang is not called.
Create subclass
Subclass by inheritance is a way to create and customize new types. New classes will keep all existing features of the class without changing the definition of the original class. For the new class type, this new subclass can be customized to only its specific functions. In addition to the relationship with the parent class or the base class, the Child class has no difference with the common class and is instantiated like a general class. Note that the parent class is mentioned in the subclass declaration below:
Class EmplAddrBookEntry (AddrBookEntry): '''employee Address Book Entry class''' # Employee Address Book class def _ init _ (self, nm, ph, id, em ): addrBookEntry. _ init _ (self, nm, ph) self. empid = id self. email = em def updateEmail (self, newem): self. email = newem print 'updated e-mail address for: ', self. name
Now we have created the first subclass, EmplAddrBookEntry. In Python, when a class is derived, the subclass inherits the attributes of the base class. Therefore, in the above class, we not only define \ _ init \\_(), the UpdateEmail () method, and the EmplAddrBookEntry also inherits the updatePhone () method from the AddrBookEntry.
If needed, it is better for each subclass to define its own constructor. Otherwise, the constructor of the base class will be called. However, if the subclass overrides the constructor of the base class, the constructor of the base class will not be automatically called. In this way, the constructor of the base class must be explicitly written to be executed, as we did above, use AddrBookEntry. \\_ init \\_ () sets the name and phone number. Our subclass also sets two additional instance attributes in the following lines of the constructor: employee ID and email address.
Note: here we need to explicitly pass the self instance object to the base class constructor, because we do not call that method in this instance but in a subclass instance. Because we do not call it through an instance, this unbound method call needs to pass an appropriate instance (self) to the method.
Subclass
> > > john = EmplAddrBookEntry('John Doe', '408-555-1212', 42, 'john@spam.doe')> > > john> > > john.name> > > john.phone> > > john.email> > > john.updatePhone('415-555-1212')> > > john.phone> > > john.updateEmail('john@doe.spam')> > > john.email