នៅក្នុងថ្នាក់ក៏ដូចជានៅក្រៅថ្នាក់ដែរ ការយក data attribute ទៅប្រើ ត្រូវធ្វើឡើងតាមរយៈថ្នាក់ឬតាមរយៈ instance នៃថ្នាក់របស់ data attribute នោះ។ ពិនិត្យកម្មវិធីខាងក្រោមនេះ៖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Area(): pi = 3.14 def __init__( self , width, height): self .display(width, height) def rectangle( self , width, height): area = width * height return area def display( self , width, height): print ( 'pi is' , Area.pi) print ( 'The area of the rectangle is' , self .rectangle(width, height)) instance = Area( 25 , 5 ) print (Area.pi) |
1 2 3 | pi is 3.14 The area of the rectangle is 125 3.14 |
ក្រៅពីការយក data attribute មកប្រើ យើងក៏អាចយកទិន្នន័យនោះមកដោះដូរថ្មីបានដែរ។ ពិនិត្យកម្មវិធីខាងក្រោមនេះ៖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Area(): pi = 3.14 def __init__( self , width, height): self .display(width, height) def rectangle( self , width, height): area = width * height return area def display( self , width, height): print ( 'pi is' , Area.pi) print ( 'The area of the rectangle is' , self .rectangle(width, height)) Area.pi = 3.1415 print ( 'The new pi is' , Area.pi) |
1 | The new pi is 3.1415 |
យើងត្រូវធ្វើការកត់សំគាល់ថា ការយក data attribute មកដោះដូរថ្មី គឺត្រូវធ្វើឡើងតែតាមរយៈថ្នាក់របស់វាតែប៉ុណ្ណោះ។ យើងមិនអាចយកទិន្នន័យនោះ មកធ្វើការដោះដូរតាមរយៈ instance នៃថ្នាក់របស់វាបានឡើយ យើងនឹងដឹងថាមកពីហេតុអ្វីនៅពេលខាងមុខនេះ៕