Python中的访问修饰符:公有(Public)、私有(Private)和受保护(Protected)
Access modifiers are used by object oriented programming languages like C++,java,python etc. to restrict the access of the class member variable and methods from outside the class. Encapsulation is an OOPs principle which protects the internal data of the class using Access modifiers like Public,Private and Protected.
Python支持三种访问修饰符,分别是public(公有)、private(私有)和protected(受保护)。这些访问修饰符对于从类外部的任何对象访问类的成员变量和方法提供了限制。
Public Access Modifier
By default the member variables and methods are public which means they can be accessed from anywhere outside or inside the class. No public keyword is required to make the class or methods and properties public.Here is an example of Public access modifier −
Example
The student class has two member variables, name and age and a method display which prints the member variable values.Both these variables and the methods are public as no specific keyword is assigned to them.
class Student: def __init__(self, name, age): self.name = name self.age = age def display(self): print("Name:", self.name) print("Age:", self.age) s = Student("John", 20) s.display() 登录后复制