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相关下载源
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[']']<dictbase['[']):
            dictbase[']']+=1
        else:
            pass
#print("'['and']'count:",dictbase)
if (dictbase['[']==dictbase[']']) & (dictbase['[']!=0):
    print("OK!")
elif dictbase['[']!=0:
    print("NOT OK!")
else:
    pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值