Carambola Python Basics Tutorial - Chapter 8: Python classes and objects (c) private property and private methods

I CSDN blog column: HTTPS: //blog.csdn.net/yty_7
Github Address: https: //github.com/yot777/Python-Primary-Learning

 

8.3 private attributes and private methods

Private property: two underscores at the beginning stating that the property is private and can not be used or accessed directly outside the class.

Private property syntax: __ attribute name

In the method of this property class is written inside the self .__ attribute name

Private methods: two underscores at the beginning, the method is declared as private methods, you can not call outside the class.

Private method syntax: __ method name

Internal class call this method of writing is self .__ method name

 

Python private attributes Example :

class Dog:
  #公有属性
  types = '泰迪'
  name = '小黑'
#私有属性
  __hair = '棕色'

dog1=Dog()
print(dog1.types)
print(dog1.name)
print(dog1.hair)

运行结果:
泰迪
小黑
Traceback (most recent call last):
  File "335.py", line 16, in <module>
    print(dog1.hair)
AttributeError: 'Dog' object has no attribute 'hair'

报错原因:dog1对象无法访问Dog类的私有属性hair

If you need to access private property outside the class, you need to use a class inside the setter get the value of private property method, and then a getter method returns the value of the property, the last call outside the class getter method.

Python access to the private property, for example :

class Dog:
  #公有属性
  types = '泰迪'
  name = '小黑'
  age = 3
  #私有属性
  __hair = '棕色'
  def set_hair(self):   #访问类的私有属性需要定义一个getter/setter函数对
    self.__hair='棕色' 
  def get_hair(self):
    return self.__hair

dog1=Dog()
print(dog1.types)
print(dog1.name)
print(dog1.get_hair())

运行结果:
泰迪
小黑
棕色

Java access to the private property, for example:

//Dog类
public class Dog {
  public String types = "泰迪";
  public String name = "小黑";
  public int age = 3;
  //私有属性
  private String hair = "棕色";
  
  public void setHair(String hair) {
    this.hair = hair;
  }
  public String getHair() {
    return hair;
  }
}

DogTest类
public class DogTest {
  public static void main(String[] args) {
    Dog dog1 = new Dog();
    System.out.println(dog1.types);
    System.out.println(dog1.name);
    System.out.println(dog1.getHair());
  }
}

运行结果:
泰迪
小黑
棕色

Reference Tutorial:

Liao Xuefeng of Python tutorials

https://www.liaoxuefeng.com/wiki/1016959663602400

Liao Xuefeng's Java Tutorial

https://www.liaoxuefeng.com/wiki/1252599548343744

Python3 Tutorial | Tutorial rookie
https://www.runoob.com/python3/
 

If you feel Benpian chapter has helped you, welcome attention, comments, thumbs up! Github welcome you Follow, Star!
 

Published 25 original articles · won praise 3 · Views 2156

Guess you like

Origin blog.csdn.net/yty_7/article/details/104206263