인캡슐레이션(캡슐화)
인스턴스 변수의 특성
Python
1 2 3 4 5 6 7 8 9 10 11 | class C( object ): def __init__( self , v): self .value = v def show( self ): print ( self .value) c1 = C( 10 ) print (c1.value) c1.value = 20 print (c1.value) c1.show() |
1 2 3 | 10 20 20 |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 | class C def initialize(v) @value = v end def show() p @value end end c1 = C . new ( 10 ) # p c1.value # c1.value = 20 c1.show() |
1 |
set / get 메소드
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 | class C( object ): def __init__( self , v): self .value = v def show( self ): print ( self .value) def getValue( self ): return self .value def setValue( self , v): self .value = v c1 = C( 10 ) print (c1.getValue()) c1.setValue( 20 ) print (c1.getValue()) |
1 2 | 10 20 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class C def initialize(v) @value = v end def show() p @value end def getValue() return @value end def setValue(v) @value = v end end c1 = C . new ( 10 ) # p c1.value p c1.getValue() # c1.value = 20 c1.setValue( 20 ) p c1.getValue() |
1 2 | 10 20 |
set/get 메소드를 사용하는 이유
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Cal( object ): def __init__( self , v1, v2): if isinstance (v1, int ): self .v1 = v1 if isinstance (v2, int ): self .v2 = v2 def add( self ): return self .v1 + self .v2 def subtract( self ): return self .v1 - self .v2 def setV1( self , v): if isinstance (v, int ): self .v1 = v def getV1( self ): return self .v1 c1 = Cal( 10 , 10 ) print (c1.add()) print (c1.subtract()) c1.setV1( 'one' ) c1.v2 = 30 print (c1.add()) print (c1.subtract()) |
1 2 3 4 | 20 0 40 -20 |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Cal attr_reader :v1, :v2 attr_writer :v1 def initialize(v1,v2) @v1 = v1 @v2 = v2 end def add() return @v1+@v2 end def subtract() return @v1-@v2 end def setV1( v ) if v .is_a?(Integer) @v1 = v end end def getV1() return @v1 end end c1 = Cal.new(10,10) p c1.add() p c1.subtract() c1.setV1( 'one' ) c1.v1 = 20 p c1.add() c1.getV1() |
1 2 3 | 20 0 30 |
속성
수업에서는 구분하지 않았습니다만 외부에서 접근 가능한 변수를 파이썬은 property 루비는 attribute라고 합니다.
Python
1 2 3 4 5 6 7 8 | class C( object ): def __init__( self , v): self .__value = v def show( self ): print ( self .__value) c1 = C( 10 ) #print(c1.__value) c1.show() |
1 |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class C #attr_reader :value #attr_writer :value attr_accessor :value def initialize(v) @value = v end def show() p @value end end c1 = C . new ( 10 ) p c1.value c1.value = 20 p c1.value |
1 2 | 10 20 |