類とキューブの方法

2451 ワード

一、クラスとオブジェクト
  • パッケージ:情報隠蔽技術では、キーワードclassを使用してpythonクラスを定義できます.キーワードの後ろには、クラスの名前、セミコロン、クラスの実装が続いています.
  • class Turtle:
        color ='green'
        weight = 10
        legs = 4
        shell = True
        mouth = ' '
        
        # 
        def climb(self):
            print(' ')
            
        def run(self):
            print(' ')
            
        def bite(self):
            print(' , ')
    
    # 2  : 
    class MyList(list):
        pass
    
    lst = MyList([1,5,2,7,8])
    lst.append(9)
    lst.sort()
    print(lst)
    
    # 3.  , 
    class Animal:
        def run(self):
            raise AttributeError(' ')
            
    class People(Animal):
        def run(self):
            print(' ')
            
    class Pig(Animal):
        def run(self):
            print('pig is walking')
            
    class Dog(Animal):
        def run(self):
            print('dog is running')
            
    def func(animal):
        animal.run()
        
    func(Pig())
    

    self
    #  , ,
    #  , self。 , self 
    class Ball:
        def setName(self,name):
            self.name = name
            
        def kick(self):
            print(" %s, , ……"%self.name)
            
    a = Ball()
    a.setName(' A')
    b = Ball()
    b.setName(" B")
    c = Ball()
    c.setName(' c')
    a.kick()
    b.kick()
    

    コンポジット
    class Turtle:
        def __init__(self,x):
            self.num = x
            
        
        
    class Fish:
        def __init__(self,x):
            self.num = x
            
    class Pool:
        def __init__(self,x,y):
            self.turtle = Turtle(x)
            self.fish = Fish(y)
            
        def print_num(self):
            print(" %s , %s "%(self.turtle.num,self.fish.num))
            
    p = Pool(2,3)
    p.print_num()
    

    次の方法で遊園地のチケットのクラスを定義し、大人2人+子供1人の平日料金を計算します。

    # , 2 
    """
     100 
     120%
     
    """
    
    class Ticket():
        def __init__(self,weekend = False,child=False):
            self.exp = 100
            if weekend:
                self.inc = 1.2
            else:
                self.inc = 1
            
            if child:
                self.discount = 0.5
            else:
                self.discount = 1
            #self.price = 120
            
        def calcPrice(self,num):
            return self.exp*self.inc*self.discount*num
        
    adult = Ticket()
    child = Ticket(child = True)
    print("2 +1 :%.2f"%(adult.calcPrice(2)+child.calcPrice(1)))
    

    キューブの方法

    #  , __init__
    #  cls , self