Python 访问控制
Java 中采用 public, protected, private 等修饰符来控制访问, Python 则采用命令约定来控制访问,一个下划线_开头表示保护方法,两个下划线__开头表示私有方法
Python 使用 @property 和 property setter 来控制属性的访问
import pytest
class Task:
def __init__(self, note: str):
self.note = note
self._status = "created"
# public method 公共方法
def format_note(self) -> str:
return self.note.title()
# protected method 保护方法
def _format_note(self) -> str:
return self.note.title()
# private method 私有方法
def __format_note(self) -> str:
return self.note.title()
@property
def status(self):
return self._status
@status.setter
def status(self, value):
allowed_values = ["created", "started", "completed", "suspended"]
if value in allowed_values:
self._status = value
print(f"task status set to {value}")
else:
print(f"invalid status: {value}")
def test_class_access():
task = Task(note="python book")
assert task.format_note() == "Python Book"
assert task._format_note() == "Python Book"
with(pytest.raises(AttributeError)):
assert task.__format_note() == "Python Book"
# __private_method -> _ClassName__private_method
# 使用 _ClassName__private_method 访问私有方法
assert task._Task__format_note() == "Python Book"
标签:status,__,format,Python,self,note,访问控制
From: https://www.cnblogs.com/goallin/p/17624624.html