នៅក្នុងថ្នាក់មួយ បើសិនជាមាន attribute ផ្សេងៗមានសញ្ញា _ ពីរនៅពីមុខ attribute ទាំងនោះនឹងមិនអាចត្រូវយកទៅប្រើនៅខាងក្រៅថ្នាក់ ដោយប្រើប្រាស់ឈ្មោះដូចនោះបានឡើយ។ ពិនិត្យកម្មវិធីខាងក្រោមនេះ៖
1 2 3 4 5 6 7 8 9 10 11 | class Cash(): def __init__( self , money = 0 ): self .__money = money def display( self ): print ( self .__money) sale = Cash( 1000 ) sale.display() print (sale.__money) |
1 2 3 4 5 | 1000 Traceback (most recent call last): File "C:/pythonProject/main.py" , line 11, in <module> print(sale.__money) AttributeError: 'Cash' object has no attribute '__money' |
គ្រប់ attribute នៅក្នុងថ្នាក់ដែលមានសញ្ញា _ នេះពីរនៅពីមុខគឺជា private attribute ពីព្រោះវាមិនអាចត្រូវយកទៅប្រើនៅខាងក្រៅថ្នាក់របស់វាបានឡើយ។ ក៏ប៉ុន្តែ បើយើងពិតជាចង់យក private attribute ទាំងឡាយទៅប្រើប្រាស់នៅខាងក្រៅថ្នាក់មែននោះ យើងត្រូវធ្វើដូចខាងក្រោមនេះ៖
1 2 3 4 5 6 7 8 9 10 11 | class Cash(): def __init__( self , money = 0 ): self .__money = money def display( self ): print ( self .__money) sale = Cash( 1000 ) sale.display() print (sale._Cash__money) |
1 2 | 1000 1000 |