One 、 class 、 Object overview
Two 、 Class definition and use
3、 ... and 、 Class properties and class method calls
Four 、 Private members and public members
summary
Python It has been an object-oriented language since the beginning of design , Because of that , stay Python It's easy to create a class and object in .
One 、 class 、 Object overviewIn object-oriented programming , Encapsulate data and operations on data , Form a whole ( object ), Different objects communicate or synchronize through message mechanism . Classify objects of the same type 、 After abstraction , Get common features and form a class .
Class abstraction includes two aspects :
1. Data abstraction : Describe the properties or states common to certain types of objects .
2. Procedural abstraction : Describe the behaviors or functional operations common to certain objects .
stay python in , Use classes to define objects of the same type . Classes are generalized data types , Ability to define the characteristics of complex data , Include :
1. static characteristic ( Data abstraction ): When creating a class, a member that represents the characteristics of an object in the form of a variable is called an attribute ( Data member ).
2. Dynamic characteristics ( Behavior abstraction , That is, how to operate the data ): Members that represent the behavior of an object in a functional form are called member methods , Data members and member methods are collectively referred to as class members .
Class is an important method to realize code reuse and design reuse , encapsulation 、 Inherit 、 Polymorphism is one of the three elements of object-oriented programming .
Classes are abstract templates for generating objects , Objects are concrete instances created from classes .
Two 、 Class definition and usePython Use class Keyword to define the class ,class The keyword is followed by a space , Next is the name of the class , If you derive from other base classes, you need to put all the parent classes in a pair of parentheses and separate them with commas , Then there is a colon , Finally, wrap the line and define the internal implementation of the class .
The first letter of the class name should be capitalized .
class Car(object): # Define a class , Derive from object class ( Ancestors of all classes , When a class is defined, if no other parent class exists, write object)can_move=True # Defining class properties def infor(self): # Define member methods print("This is a car")
There is only one special difference between a class method and a normal function —— They must have an additional first parameter name , By convention its name is self(self Represents an instance of a class , Not class ;self No python keyword , We can replace him with another one ).
3、 ... and 、 Class properties and class method callsAfter defining a class , Can be used to instantiate objects , And pass “ Object name . member ” To access data members or member methods .
>>>spring=Bird() # Instantiate objects >>>print(Bird.have_feather) # Call properties... By class name >>>print(Bird.have_head) # Call properties by object name >>>spring.move() # Call method by object name >
Class methods are generally divided into 3 class , Class methods 、 Instance methods and static methods , The instance method is the most used . We know , The calling methods of instance methods actually include 2 Kind of , You can use class object call , It can also be called directly through the class name .
Usually , We are used to using class objects to call instance methods in classes . But if you want to call instance methods with classes , It can't be like this :
class Study: def info(self): print(" learn Python")# Call the instance method directly through the class name Study.info()
Run the above code , The program will report the following error :
Traceback (most recent call last):
File "D:\python3.6\demo.py", line 5, in <module>
Study.info()
TypeError: info() missing 1 required positional argument: 'self'
among , The error message in the last line reminds us , call info() Class method is missing self Parameter transfer . It means , Unlike calling instance methods with class objects , When the instance method is called directly through the class name ,Python It doesn't automatically give self Parameter values .
Readers should also understand ,self The argument requires the actual caller of the method ( It's a class object ), Only the class name is provided here , Of course, the value cannot be transferred automatically .
therefore , If you want to call the instance method directly through the class name , You have to manually self Parameter values . For example, change the above code to :
class Study: def info(self): print(" learn Python")clang = Study()# Call the instance method directly through the class name Study.info(clang)
Run the program again , The result is :
learn Python
You can see , By hand clang This class object was passed to self Parameters , Make the program execute correctly . actually , The form of calling instance method here is completely equivalent to clang.info().
It is worth mentioning that , The error message above just let us manually for self Parameter values , But there is no rule that an object of this class must be passed , In fact, a parameter can be passed in at will , for example :
class Study: def info(self): print(self," learn Python")# Call the instance method directly through the class name Study.info("zhangsan")
The running result is :
zhangsan learn Python
You can see ,“zhangsan” This string was passed to info() Methodical self Parameters . obviously , Whether it's info() Method used in self Parameters call other class methods , Or use self Parameter to define a new instance variable , Give it in a mess self Parameter passing will cause the program to crash .
in general ,Python Class names are allowed to call instance methods directly , But it has to be done manually for the first self Parameter passing parameter , This way of calling methods is called “ Unbound method ”.
The way to access a class member with an instance object of a class is called a binding method , The way to call class members with class names is called unbound methods .
Four 、 Private members and public membersPrivate members cannot be accessed directly outside the class , It is generally accessed and operated inside the class , Or you can call the public member method of the object outside the class to access , Public members can be used publicly , Both can be accessed inside the class , It can also be used in external programs .
In form , When defining members of a class , If the member name starts with two underscores but does not end with two underscores, it means that it is a private member , Otherwise it is not a private member .
Python No strict access protection mechanism for private members , In a special way “ Object name ._ Class name __xxx” You can also access private members in external programs , But this destroys the encapsulation of the class , This is not recommended .
stay Python in , Variable names and method names that begin with underscores have special meanings , Especially in the definition of classes .
_xxx: Protected members ;
__xxx__: Special members of the system definition ;
__xxx: Private member , Only class objects can access , Subclass objects cannot directly access this member , But outside the object, you can use “ Object name ._ Class name __xxx” This is a special way to access .
Be careful :Python There is no private member in the strict sense of .
summaryThis is about Python This is the end of the article on calling class attributes and methods , More about Python Please search the previous articles of the software development network or continue to browse the following related articles. I hope you can support the software development network in the future !