상속이란
상속의 문법 - Python
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Class1( object ): def method1( self ): return 'm1' c1 = Class1() print (c1, c1.method1()) class Class3(Class1): def method2( self ): return 'm2' c3 = Class3() print (c3, c3.method1()) print (c3, c3.method2()) class Class2( object ): def method1( self ): return 'm1' def method2( self ): return 'm2' c2 = Class2() print (c2, c2.method1()) print (c2, c2.method2()) |
1 2 3 4 5 | <__main__.Class1 object at 0xb757dfec> m1 <__main__.Class3 object at 0xb758704c> m1 <__main__.Class3 object at 0xb758704c> m2 <__main__.Class2 object at 0xb758708c> m1 <__main__.Class2 object at 0xb758708c> m2 |
상속의 문법 - Ruby
1 2 3 4 5 6 | #<Class1:0x0000000270dee0> "m1" #<Class3:0x0000000270dcb0> "m1" #<Class3:0x0000000270dcb0> "m2" |
상속의 응용
Python
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 | 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 class CalMultiply(Cal): def multiply(self): return self.v1*self.v2 class CalDivide(CalMultiply): def divide(self): return self.v1/self.v2 c1 = CalMultiply(10,10) print(c1.add()) print(c1.multiply()) c2 = CalDivide(20,10) print(c2, c2.add()) print(c2, c2.multiply()) print(c2, c2.divide()) |
1 2 3 4 5 | 20 100 < __main__.CalDivide object at 0x000000000316CDA0> 30 < __main__.CalDivide object at 0x000000000316CDA0> 200 < __main__.CalDivide object at 0x000000000316CDA0> 2.0 |
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 30 31 32 33 34 35 36 37 38 39 | 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 class CalMultiply < Cal def multiply() return @v1 * @v2 end end class CalDivide < CalMultiply def divide() return @v1 / @v2 end end c1 = CalMultiply. new ( 10 , 10 ) p c1.add() p c1.multiply() c2 = CalDivide. new ( 20 , 10 ) p c2, c2.add() p c2, c2.multiply() p c2, c2.divide() |
1 2 3 4 5 6 7 8 | 20 100 #<CalDivide:0x0000000289c108 @v1=20, @v2=10> 30 #<CalDivide:0x0000000289c108 @v1=20, @v2=10> 200 #<CalDivide:0x0000000289c108 @v1=20, @v2=10> 2 |