데이터 숨기기 :
는 우발적이거나 악의적 인 수정으로부터 데이터를 보호합니다. 내부 속성에 대한 직접적인 액세스를 제한함으로써 데이터 무결성을 보장하고 예기치 않은 동작을 방지합니다.<code class="python">class BankAccount: def __init__(self, account_number, initial_balance): self.__account_number = account_number # Private attribute self.__balance = initial_balance # Private attribute def get_balance(self): return self.__balance def deposit(self, amount): if amount > 0: self.__balance += amount return f"Deposited ${amount}. New balance: ${self.__balance}" else: return "Invalid deposit amount." def withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount return f"Withdrew ${amount}. New balance: ${self.__balance}" else: return "Insufficient funds or invalid withdrawal amount." # Example usage account = BankAccount("1234567890", 1000) print(account.get_balance()) # Accessing balance through getter method print(account.deposit(500)) print(account.withdraw(200)) #print(account.__balance) # This will raise an AttributeError because __balance is private. Trying to directly access it outside the class is prevented.</code>및
__account_number
는 개인 속성입니다. 이중 밑줄 밑줄 접두사 ()는 이름 Mangling을 구현하여 클래스 외부에서 액세스 할 수 없습니다. 액세스 및 수정은 __balance
, __
및 방법을 통해 제어됩니다. 이는 균형의 직접적인 조작을 방지하여 데이터 무결성을 보장하고 우발적 인 오류를 방지합니다. 이 방법은 또한 비즈니스 규칙을 시행합니다 (예 : 철수가 부정적인 금액의 잔액 또는 예금을 초과하는 방지). 이는 캡슐화가 데이터 보호, 코드 조직 및 유지 관리를 향상시키는 방법을 보여줍니다.위 내용은 캡슐화 란 무엇이며 왜 파이썬에서 중요한가?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!