Content of this section

1、 summary

2、 Access properties

3、 Private property

4、 summary

One 、 summary

In the last blog, we've talked about classes , Let's review the following :

  1. Defining classes (class dog(object))-> Instantiation (d = dog()) -> Instantiate objects (d)
  2. __init__() Constructors
  3. self.name = name It's called attribute 、 Member variables 、 Field
  4. def sayhi(self)  It's called the method 、 Dynamic properties

Let's continue to learn about the features of classes .

Two 、 Access class properties

2.1 Member variables and parameters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class  dog( object ):
     "dog class"
 
     def  __init__( self ,name):
         self .name  =  name    # Member variables of class
                
     def  sayhi( self ):
         print ( "the dog {0} is sayhi" . format ( self .name))
 
     def  eat( self ,food):    # Pass in a parameter , Parameter name :food
         print ( "the dog name is {0},it like food is {1}" . format ( self .name,food))
 
=  dog( "alex" # Instantiate objects
d.sayhi()    # transfer sayhi Method
d.eat( "hotdog" )   # transfer eat Method
 
# Output
the dog alex  is  sayhi
the dog name  is  alex,it like food  is  hotdog

① A lot of people have questions , Why? eat Method will pass in a food The parameter name of ? Why can't this be used in other ways ? and self.name It's OK ?

because food It's just for eat Method , Not a member variable of a class , You can only use it in your own way , and self.name Is a member variable of the class , It's a property of a class , So it can be called .

② Why is the first parameter of every method of a class self Well ?

Because when the class is instantiated , You need to pass in the instance object itself , OK, call the properties and methods of the object itself .

2.2 Modify the properties of an object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class  dog( object ):
     "dog class"
 
     def  __init__( self ,name,age):
         self .name  =  name  
         self .age  =  age
 
     def  sayhi( self ,update_age):   # Pass in a update_age Parameters
         self .age  =  update_age    # Modify the age attribute
 
=  dog( "alex" , 18 )
d.sayhi( 22 )   # The first 1 Modify in the method of the class
print (d.age)  
d.age  =  19    # The first 2 Modify outside the class
print (d.age)
 
# Output
22
19

notes : That is to say, you can modify the properties of a class in its methods or outside the class

3、 ... and 、 Define private properties

explain : Before we said , We can access the properties of the class , You can also modify the properties of the class at will , But once a class property is defined as private , It can't be visited outside , It can't be changed at will .

3.1 Define private properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class  dog( object ):
     "dog class"
 
     def  __init__( self ,name,age):
         self .name  =  name
         self .age  =  age
         self .__sex  =  "man"   # Define private properties __sex
 
     def  sayhi( self ,update_age):
         self .age  =  update_age
 
=  dog( "alex" , 18 )
print (d.__sex)  # Access private properties __sex
 
# Output
Traceback (most recent call last):
   File  "E:/PycharmProjects/pythontest/day6/ encapsulation .py" , line  16 in  <module>
     print (d.__sex)
AttributeError:  'dog'  object  has no attribute  '__sex'   # Report errors , Say no __sex This attribute

As can be seen from the above example , Private properties are not accessible , It can't be modified . But we just want to visit , But don't modify , What shall we do ?

3.2 get Method to access private properties

Although we can't access private properties externally , But we can access private properties inside the class , So we use the following method , Access private properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class  dog( object ):
     "dog class"
 
     def  __init__( self ,name):
         self .name  =  name
         self .__sex  =  "man"   # Define private properties sex
 
     def  get_sex( self ):   # Definition get Method
         return  self .__sex    # Return private property sex value
 
=  dog( "alex" )
d_sex  =  d.get_sex()   # Call instance object d Of get_sex() Method to get private properties sex
print (d_sex)
 
# Output
man

notes : This method can only access private properties , But you can't change private properties

3.3 Enforce access to private properties

The above method can only access , But it can't be modified , The following method is more violent , Can be accessed or modified , Namely : Object name ._ Class name __ Property name

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class  dog( object ):
     "dog class"
 
     def  __init__( self ,name):
         self .name  =  name
         self .__sex  =  "man"   # Define private methods sex
 
=  dog( "alex" )
print (d._dog__sex)   # Access private properties sex
d._dog__sex  =  "woman"   # Modify private properties sex
print (d._dog__sex)  # Print the modified value
# Output
man
woman

Four 、 summary

  1. Define private properties :self.__private_attr_name = private_attr_name
  2. Enforce access to private properties : Object name ._ Class name __ Property name (d._dog__sex)
  3. Provide read-only interface access to the outside world :

def get_sex(self):

return self.__sex

object-oriented 【day07】: Class ( Four ) More articles about

  1. Python Basics Object oriented two The three major characteristics

    Python Basics Object oriented two The three major characteristics The last one mainly introduced Python in , Object oriented class and object definition and simple application of instance , This article continues to talk about , In this article, we will focus on :Python Class members . become ...

  2. Microsoft is in .NET 3.5 I added a new one HashSet class , stay .NET 4 I added a new one SortedSet class , This article introduces their characteristics , And compare their similarities and differences .

    Microsoft is in .NET 3.5 I added a new one HashSet class , stay .NET 4 I added a new one SortedSet class , This article introduces their characteristics , And compare their similarities and differences . .NET Collection Function library Has ...

  3. object-oriented 、 Classes and objects 、 Members and local variables 、 encapsulation 、private、 Constructors 、this、static、extends、super、final、abstract、interface、 polymorphic 、 Inner class 、 abnormal 【5】

    If there is something wrong , Please understand and welcome criticism , Not very grateful . Please respect the author's work : The original author of this article :pipi-changing Original source of this article :http://www.cnblogs.com/pipi-changing ...

  4. Java Object oriented overview and three characteristics

    Java Is an object-oriented high-level programming language , Classes and objects are Java The core of the program . Around Java Classes and Java object , There are three basic characteristics : The package is Java Class specification . Inheritance is a form of association between classes . And polymorphism ...

  5. [.net Advanced object oriented programming ] (12) serialize (Serialization)( Four ) Fast grasp JSON Serialization and deserialization of

    [.net  Advanced object oriented programming ] (12)  serialize (Serialization)( Four )  Fast grasp JSON Serialization and deserialization of This section is a guide to : Introduce JSON Structure , stay JS The use of . Key points JSON How to be in .N ...

  6. 【 turn 】Python Object oriented and class

    [ turn ]Python Object oriented and class Content of this section The concept of object orientation Class encapsulation Class inheritance Class polymorphism Static methods . Class method and Attribute method Class The problem of the order in which the attributes are searched by the instance objects of subclasses in the inheritance hierarchy One . Face right ...

  7. ( turn ) object-oriented ——UML The class diagram design

    background : all the time , Yes UMl The drawing method of class diagram is not very clear , But with the deepening of learning , Discover and master UML Class diagram , Be able to better understand the logic between codes , And that's the foundation of programming , So it's necessary to put UML Have a good grasp of . UML Class diagram novice Introduction ...

  8. Solr Series six :solr Search details optimize query results ( Faceted search 、 Search results highlight 、 Query suggestions 、 Collapse the result 、 The results were grouped 、 Other search features )

    One . Faceted search 1. What is faceted search ? Faceted search : On the basis of the search results, make statistics according to the specified dimensions , To show the other side of the search results . Be similar to SQL Of the statement group by An example of faceted search : http://localhos ...

  9. Cattle from Java The object-oriented of knowledge points java Four characteristics of ( abstract 、 encapsulation 、 Inherit 、 polymorphic )

    Not much to say , Direct delivery of dry goods ! object-oriented java The four characteristics of the abstract Abstract means a little vague , I'm not sure what it means . Like , To define a method and class . But we haven't decided how to implement its specific sub method yet , Then I can use abstract classes or interfaces . Specifically ...

Random recommendation

  1. word file Set multiple picture sizes at once

    1. open WORD file , Insert multiple images . 2. stay word Press alt+f11 Composite key , Get into VBA Pattern . 3. Find your... In the Project Explorer on the left word file , Right click on it / add to / modular 4. Copy the following code Sub Ma ...

  2. Baidu Maps API Custom map

    http://api.map.baidu.com/lbsapi/creatmap/index.html http://developer.baidu.com/map/index.php?title=w ...

  3. Office 365 - SharePoint 2013 Online Master page and page layout

    1. open https://login.microsoftonline.com, land , Click on SharePoint, Here's the picture : 2. Open the site collection , You can see . add to . Delete and other management operations : 3. Open a site , Here's the picture : 4. ...

  4. wxPython Simple introduction

    wxPython brief introduction wxPython yes Python A good set of languages GUI Graphics library , allow Python It's very convenient for programmers to create complete . All function keys  GUI The user interface . wxPython It's as good as ...

  5. canva Practice small examples —— Mosaic effect

    Before we brought the operation of pixels API, At the moment , I think it should be further explained and demonstrated with small examples , In order to bring you a broader vision and inspiration , You've read so many of my articles , You should know my style , I don't say much nonsense , Get to the point : This time for the big one ...

  6. JAX-WS( 3、 ... and ) Simple to build webservice Deploy to tomcat On

    Preface : Although building local jax-ws Of webservice It's simple , But to deploy to tomcat It's going to go around the bend . tomcat Itself and the jdk None jaw-ws Of API, So we need to do something extra when we deploy , There are two options 1 ...

  7. /****************** Attributes ********************/

    /* Text for predefined character properties . If the key is not in the dictionary , Then use the default values , As follows . */ The following attributes are IOS6 Of NSVerticalGlyphFormAttributeName NS_AVAILABLE_IOS( ...

  8. jquery uploadify Modify the upload file name and display

    If you think it's too much trouble to read articles , You can look directly at the reference :http://stackoverflow.com/questions/7707687/jquery-uploadify-change-file-name-as-i ...

  9. ASP.NET Core MVC – Caching Tag Helpers

    brief introduction Caching can greatly improve application loading time and response speed . We can use caching Tag Helpers The cache doesn't change much HTML Content . In the last article , We talked about Tag Helpers, demonstration Tag Helpers can ...

  10. EF Code First Connect MySql

    Read a lot of articles , I tried many times, but I couldn't go on , Sort it out , So that I can see . 1. establish ASP.NET MVC project (EFCodeFirst) 1.1. Right click on the reference and select Manage NuGet Package download MySql.Data. ...