Python類の_init__()メソッド

2595 ワード

クラスの_init__()メソッド
Step 1:プロセス向け
def getPeri(a,b): 
    return (a + b)*2 
def getArea(a,b): 
    return a*b 
    
#test:
print(getPeri(3,4))
print(getArea(3,4))

Step 2:ダミーオブジェクト
class Rectangle_po(): 
    def getPeri(self,a,b): 
        return (a + b)*2 
    def getArea(self,a,b): 
        return a*b 
 
#test:   
rect_po = Rectangle_po()
print(rect_po.getPeri(3,4)) 
print(rect_po.getArea(3,4)) 
print(rect_po.__dict__)   #  rect_po     

Step 3:オブジェクト向け
import math
class Rectangle_oo(): 
    def __init__(self,a,b):
        self.a=a
        self.b=b      
    def getPeri(self): 
        return (self.a + self.b)*2 
    def getArea(self): 
        return self.a*self.b 
    def getdistance(self,Px,Py):   #Px Py        
        d=(self.a-Px)**2+(self.b-Py)**2
        return math.sqrt(d)

#test:
rect_oo = Rectangle_oo(3,4)
print(rect_oo.getPeri())
print(rect_oo.getArea())
print(rect_oo.getdistance(0,0))
print(rect_oo.__dict__)   #  rect_oo     

(1)クラスで定義しない_init__()メソッドは、クラスのインスタンスを定義し、クラスを呼び出すメソッドでもあります.でも、__でdict__クラスインスタンスのプロパティを表示する場合、プロパティは空です.クラスをインスタンス化する場合は、初期化パラメータを入力する必要はありませんが、インスタンスがクラスを呼び出す各メソッドには、入力パラメータが必要です(同じパラメータが繰り返し入力されます)
以上のようにPoクラスのrect_Poインスタンス
(2)クラスで定義_init__()メソッドは、インスタンスを作成するときに通常のフィールドをバインドし、クラスメソッドを定義して呼び出すときに重複するパラメータを必要とせず、オブジェクト向けのプログラミングのようになります.
Anaconda関連ダウンロードソース
  • https://repo.continuum.io/archive/?spm=5176.100239.blogcont109288.14.H9Tlkq
  • Anaconda往期バージョンを含む清華大学ミラーhttps://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/
  • Anaconda公式サイトhttps://www.anaconda.com/download/#_windows’

  • Test
    Your task in this exercise is as follows: Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Generate a string with N opening brackets ("[") and N closing brackets ("]"), in some arbitrary order. Examples:
       []        OK   ][        NOT OK
       [][]      OK   ][][      NOT OK
       [[][]]    OK   []][[]    NOT OK
    
    s=input('type several [ and ]:')
    dictbase={'[':0,']':0}
    if s.count('[')!=s.count(']'):
        print("'[' and ']'have different number")
    else:
        for i in s:
            if i=='[':
                dictbase['[']+=1
            elif (i==']') & (dictbase[']']