Python类的__init__()方法

类的__init__()方法

Step1:面向过程

def getPeri(a,b): 
    return (a + b)*2 
def getArea(a,b): 
    return a*b 
    
#test:
print(getPeri(3,4))
print(getArea(3,4))

Step2:假的面向对象

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实例的属性

Step3:面向对象

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__查看类实例的属性时,属性为空; 实例化类时,不需要传入初始化参数,但实例调用类的每个方法时都需要传入参数(相同参数重复传入)
如上Rectangle_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[']']

你可能感兴趣的:(Python)