python常用方法大全-python中常用的方法

#-*-coding:utf-8-*-

"""

__init__方法

创建一个类的新实例时,参数被包括在圆括号内跟在类名后面,从而被传递给__init__方法

"""

# class Person:

# def __init__(self,name):

# self.name = name

# def sayHi(self):

# print("Hello,my name is",self.name)

# p = Person("duanchunyang")

# p.sayHi()

"""

__del__方法

主要作用是释放被占用的资源,在Python中是析构函数

"""

# class Room:

# count=0

# def __init__(self,name):

# self.name = name

# print("初始化,传入的名称是%s"%self.name)

# Room.count += 1

# def __del__(self):

# print("%s 说 byebye"%self.name)

# Room.count -= 1

# if Room.count == 0:

# print("这个房间里就剩下我一个人了")

# else:

# print("这个房间里还有%d个人"%Room.count)

# def sayHi(self):

# print("大家好,我的名字是%s"%self.name)

# def howMany(self):

# if Room.count == 1:

# print("这个房间里就剩下我一个人了")

# else:

# print("这个房间里还有%d 个人"%Room.count)

# if __name__ == "__main__":

# room = Room("duochunyuan")

# room.sayHi()

# room.howMany()

# room1 = Room("lintiantian")

# room1.sayHi()

# room1.howMany()

# room.__del__()

"""

__new__方法

在创建对象时被调用,返回当前对象的一个实例,__init__是创建完对象后才被调用

"""

#

# class Mynew(object):

# def __init__(self):

# print("__init__")

# def __new__(self):

# print("__new__")

# if __name__=="__main__":

# mynew =Mynew()

# mynew

"""

__setitem__方法

简单地重定向到真正的字典self.data,让他进行运作

"""

# class MySetitem:

# def __setitem__(self, key, value):

# print("key=%s,value=%s" % (key,value))

#

# mysetitem = MySetitem()

# mysetitem["dcy"] = "duanchunyang"

# mysetitem["mxl"] = "maxianglin"

# mysetitem["ltt"] = "lintiantian"

"""

__getitem__方法

重定向到字典,返回字典的值

"""

# class MyGetitem:

# def __getitem__(self, key):

# if key == "Thank you":

# return "You are welcome!"

# elif key == "Sorry":

# return "That is all right"

# elif key == "Do you like me":

# return "T love you"

# else:

# return "you can go"

#

# if __name__=="__main__":

# mygetitem = MyGetitem()

# print(mygetitem["Thank you"])

# print(mygetitem["Sorry"])

# print(mygetitem["Do you like me"])

# print(mygetitem[""])

"""

__delitem__方法

调用"del|实例对象[key]"时调用

"""

# class MyDelitem:

# def __delitem__(self, key):

# print("delete item:%s" %key)

# mydekitem = MyDelitem()

# del mydekitem["dcy"]

"""

__cmp__方法

用来比较两个实例对象,当使用==比较类实例时,python会替你调用__cmp__专用方法

"""

class MyCmp:

def __cmp__(self, other):

print("__cmp__ is called")

return 0

if __name__ == "__main__":

mycmp1 = MyCmp()

mycmp2 = MyCmp()

print(mycmp1==mycmp2)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值