One 、 Preface
Two 、 Defining classes
3、 ... and 、 Create an instance of a class
Four 、“ Magic ” Method ——_ init _()
5、 ... and 、 Create members of the class and access
1. Create instance methods and access
2. Create data members and access
6、 ... and 、 Access restrictions
One 、 Prefacestay Python in , Class represents a collection of objects with the same properties and methods . When using classes , You need to define the class first , Then create an instance of the class , Through the instance of the class, you can access the properties and methods in the class .
Two 、 Defining classesstay Python in , Use of class definition class Keyword to implement , The grammar is as follows :
class ClassName:“”“ Help for class ”“” # Class text string statement # The class body
Parameter description :
ClassName: Used to specify the class name , It usually starts with a capital letter , If the class name includes a word , The first letter of the second word should also be capitalized , This method of naming is also called “ Hump nomenclature ”, This is the Convention . Of course , You can also name it according to your habits , But it's generally recommended to name it by convention .
“ Help for class ”: The document string used to specify the class . After defining the string , When creating objects of a class , Enter the class name and the parentheses to the left “( ” after , The message... Will be displayed .
statement: The class body , Mainly by class variables ( Or class members )、 Methods and properties, etc . When defining a class , Didn't think about the specific functions of the class , It can also be used directly in the class body Pass Sentence instead .
class Geese:""" Wild geese """pass
3、 ... and 、 Create an instance of a class After definition , It doesn't really create an instance . It's like a car design . Design drawings can tell you how the car looks , But the design itself is not a car . You can't drive it away , It can only be used to build real cars , And it can be used to make a lot of cars . So how to create an instance ?
class The statement itself does not create any instances of the class . So after the class definition is complete , You can create instances of classes , That is, instantiate the object of this class . The syntax for creating an instance of a class is as follows :
ClassName(parameterlist)
Parameter description :
ClassName: Is a required parameter , Used to specify the class .
parameterlist: You can choose parameters , When creating a class , Not created __init__() Method , Or when __init__() There is only one way self When parameters are , parameterlist It can be omitted .
for example , Create the above Geese Class , You can use the following code :
# Create a class class Geese: """ Wild geese """ pass# Create examples wildGoose = Geese()print(wildGoose)
After executing the above code , It will show something like :
As can be seen from the above execution results ,wildGoose yes Geese Class .
Four 、“ Magic ” Method ——_ init _() After creating the class , Class usually automatically creates a __init__() Method . This method is a special one , similar JAVA The construction method in language . Whenever a new instance of a class is created ,Python Will automatically execute it .init() Method must contain a parameter , And must be the first parameter .self Parameter is a reference to the instance itself , Used to access properties and methods in a class .
The actual parameters are passed automatically when the method is called self. therefore , When __init__() When the method has only one parameter , When creating an instance of a class , There is no need to specify parameters .
for example , Let's take wild geese as an example , And create __init__() Method , The code is as follows :
# Create a class class Geese: """ Wild geese """ def __init__(self): print(" I am a wild goose ")wildGoose = Geese()
Run the above code , The following will be output :
Common mistakes :
When creating a class __init__() When the method is used , Run the following code in the development environment :
# Create a class class Geese: """ Wild geese """ def __init__(): # Construction method print(" I am a wild goose ")wildGoose = Geese()# Create wild goose instance
Run the above code , The following exception will be thrown :
stay __init__() In the method , except self Out of parameters , You can also customize some parameters , Use commas... Between parameters “,” separation . for example , The following code will create __init__() When the method is used , Reassign 3 Parameters , Namely beak、wing and claw:
# Create a class class Geese: """ Wild geese """ def __init__(self, beak, wing, claw): print(" I am a wild goose ! I have some characteristics :") print(beak) print(wing) print(claw)beak_1 = " beak "wing_1 = " Wing "claw_1 = " claw "wildGoose = Geese(beak_1, wing_1, claw_1)
Run the above code , The following results will be displayed :
5、 ... and 、 Create members of the class and accessClass members are mainly composed of instance methods and data members . After creating the members of the class in the class , It can be accessed through an instance of the class . Here is a detailed introduction .
1. Create instance methods and accessThe so-called instance method refers to defining a function in a class . This function is a function that operates on an instance of a class . Same as __init__() The method is the same , The first parameter of the instance method must be self, And it must contain a self Parameters .
The syntax format of the method of creating an instance is as follows :
def functionName(self,parameterlist):block
Parameter description :
functionName: Used to specify the method name , It usually starts with a lowercase letter .
self: Necessary parameters , Represents an instance of a class , Its name can be self Other words , Use self It's just a habit .
parameterlist: Used to specify the division self Parameters other than parameters , Comma between parameters “,” separation .
block: Method body , Specific functions realized
After the instance is created , You can use the instance name and point of the class (.) Operator to access .
The specific syntax format is as follows :
instanceName.functionName(parametervalue)
Parameter description :
instanceName: Is the instance name of the class
functionName: For the name of the method to call
parametervalue: Indicates that the method specifies the corresponding actual parameters , The number of its values and the creation of instance method parameterlist The same number of .
2. Create data members and accessData members are variables defined in a class , The property , According to the defined position , It can also be divided into class properties and instance properties , Here are the introduction .
Class properties : Class attributes are defined in the class , And the properties outside the function . Class properties can share values among all instances of a class , That is, it is common in all instantiated objects .
for example , Define a wild goose , Define... In this class 3 Attributes , Used to record the characteristics of wild geese , The code is as follows :
class Geese: """ Wild geese """ beak_1 = " beak , Relatively sharp " # Defining class properties ( beak ) wing_1 = " Wing , The larger " claw_1 = " claw , Walk freely " def __init__(self): print(" I am a wild goose ! I have some characteristics :") print(Geese.beak_1) # Output beak properties print(Geese.wing_1) print(Geese.claw_1)
Create the above class Geese, Then create an instance of the class , The code is as follows :
goose = Geese() # Instantiate a wild goose's object
Run the above code to create Geese After the instance of the class , The following will be displayed :
Instance attributes :
Instance property refers to the property defined in the method of the class , Only for the current instance .
for example , Define a wild goose Geese, In this category __init__() Defined in method 3 Instance properties , Used to record the characteristics of wild geese , The code is as follows :
# Create a class class Geese: """ Wild geese """ def __init__(self): self.beak_1 = " beak , Relatively sharp " # Define instance properties ( beak ) self.wing_1 = " Wing , The larger " self.claw_1 = " claw , Walk freely " print(" I am a wild goose ! I have some characteristics :") print(self.beak_1) # Output beak properties print(self.wing_1) print(self.claw_1)
Create the above class Geese, Then create an instance of the class , The code is as follows :
goose = Geese() # Instantiate a wild goose's object
Run the above code to create Geese After the instance of the class , The following will be displayed :
explain :
Instance properties can only be accessed through the instance name . If you access instance properties through the class name , The exception shown in the figure will be thrown .
The properties of an instance can also be modified by the instance name , Different from class , After modifying the instance property through the instance name , It does not affect the corresponding instance property values in other instances of the class . for example , Define a wild goose , And in __init__() Method to define an instance property , Then create two Geese Class , And modify an instance property , Finally, the instance properties are output respectively , The code is as follows :
# Create a class class Geese: """ Wild geese """ def __init__(self): self.beak_1 = " beak , Relatively sharp " # Define instance properties ( beak ) print(self.beak_1)goose1 = Geese() # establish Geese example 1goose2 = Geese() # establish Geese example 2goose1.beak_1 = " beak , More pointed than a goose " # Modify instance properties print("goose1 Of beak_1 attribute :", goose1.beak_1)print("goose2 Of beak_1 attribute :", goose2.beak_1)
Run the above code , The following will be displayed :
6、 ... and 、 Access restrictionsYou can define properties and methods inside a class , Outside the class, you can directly call properties or methods to manipulate data , This hides the complex logic inside the class . but Python There are no restrictions on access to properties and methods . In order to ensure that some properties or methods inside the class are not accessed by the outside , You can add a single underscore in front of the property or method name (_foo)、 Double underline (__foo) Or double underline at the beginning and end ( __ foo __), To restrict access . among , Underline 、 Double underline 、 The function of double underline is as follows :
__ foo __ : Double underscores at the beginning and the end indicate the definition of special methods , Generally, the system name , Such as __init__().
_foo: A sign beginning with a single underscore protected( Protect ) Members of type , Only the class itself or subclasses are allowed to access , But you can't use “ from module impor” Statement import .
for example , Create a Swan class , Define protection properties _neck_swan, And in __init__() Method , Then create Swan Class , And output the protection attribute through the instance name _neck_swan,
The code is as follows :
class Swan: """ Swans """ _neck_swan = " The swan has a long neck " # Create private properties def __init__(self): print("__init__():", Swan._neck_swan)swan = Swan() # establish Swan class print(" Direct access :", swan._neck_swan)
Execute the above code , The following will be displayed :
From the above running results, we can see that : The protection properties can be accessed through the instance name .
__foo: Double underline means private( private ) Members of type , Only the class itself that defines the method is allowed to access , And it can't be accessed through an instance of a class , But it can go through “ Instance name of class . Class name __xxx” Access to .
for example , Create a Swan class , Define protection properties __neck_swan, And in __init__() Method , Then create Swan Class , And output the protection attribute through the instance name __neck_swan,
The code is as follows :
# Create a class class Geese: """ Wild geese """ def __init__(self, beak, wing, claw): print(" I am a wild goose ! I have some characteristics :") print(beak) print(wing) print(claw)beak_1 = " beak "wing_1 = " Wing "claw_1 = " claw "wildGoose = Geese(beak_1, wing_1, claw_1)
Run the above code , The result shown in the figure will be output :
From the above running results, we can see that : Private properties can be through “ Class name . Property name ” Access to , It can also be done through “ Instance name . Class name __xxx” Access to , But not directly through “ Instance name . Property name ” Access to .
This is about Python This is the end of the article on class definition and usage details , More about Python Please search the previous articles of SDN or continue to browse the related articles below. I hope you will support SDN more in the future !