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 class member variable and methods from outside the class. En膠囊which protects the internal data of the class using Access modifiers like Public,Private and Protected.
Python支援三種存取修飾符,分別是public(公有)、private(私有)和protected(受保護)。這些存取修飾符對於從類別外部的任何物件存取類別的成員變數和方法提供了限制。
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 required to make the class or methods
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()Output
Name: John Age: 20
Example
class BankAccount: def __init__(self, account_number, balance): self.__account_number = account_number self.__balance = balance def __display_balance(self): print("Balance:", self.__balance) b = BankAccount(1234567890, 5000) b.__display_balance()Output
AttributeError: 'BankAccount' object has no attribute '__display_balance'
Example
class Person: def __init__(self, name, age): self._name = name self._age = age def _display(self): print("Name:", self._name) print("Age:", self._age) class Student(Person): def __init__(self, name, age, roll_number): super().__init__(name, age) self._roll_number = roll_number def display(self): self._display() print("Roll Number:", self._roll_number) s = Student("John", 20, 123) s.display()Output
Name: John Age: 20 Roll Number: 123
以上是Python中的存取修飾符:公有(Public)、私有(Private)和受保護(Protected)的詳細內容。更多資訊請關注PHP中文網其他相關文章!