- # 可变类型的对象为全局变量时
- #MAP 可以直接迭代, 不需要写 for 循环了
- # 方法一:
- foo = [2,18,9,22,17]
- # mapdemo = map(lambda x:x*2+10,foo)
- # for i in mapdemo:
- # print(i)
- # #方法二:
- # def tt(x):
- # return x*2+10
- # m=tt
- # print("m={0}".format(m))
- # mresult=m(12)
- # print("mresult=%d"%mresult)
- # result=map(tt,foo)
- # print("result:{0}".format(result))
- # 加括号是函数的引用, 不加括号是调用函数
- # f=filter(lambda x:x>10,foo)# 过滤满足条件的结果
- # print(f)
- # for i in f:
- # print(i)
- #
- # #reduce() 求加减函数
- # from functools import reduce
- # # r=reduce(lambda x,y:x+y,foo)
- # # print("r={0}".format(r))
- # def re(x,y):
- # return x+y
- # r=reduce(re,foo)
- # print("r={0}".format(r))
- #
- # #算数函数直接调用
- # print(sum(foo))
- # print(max(foo))
- # print(min(foo))
- #
- # print(sorted(foo))#sorted 函数会生成一个新的列表, 不改变原来列表的值
- # print(foo)
- #
- # s=sorted(foo,reverse=True) #倒序排序
- # print(s)
- #
- # dict1={"a":1,"d":3,"c":2}
- # print(sorted(dict1.items()))
- # def _gt_(self,other):
- # if self.obj>other:
- # self.obj=obj
- #
- # print(sorted([1,2,3,4,5,6,7],key=reversed_cmp()))
- #.sort() 对原来的列表进行排序后会更新原来列表的值, 没有返回值 sorted 函数会生成一个新的列表, 不改变原来列表的值 并且有返回值
- # a=['bbb','aaa','CCV','Zoo']
- # print(sorted(a,key=str.lower))# 根据字符串大小写进行排序
- #
- # #self 代表当前对象
- # class Person:
- # def __init__(self,sex=None):# 初始化函数
- # self.sex=sex
- # def eat(self):
- # print("正在吃饭")
- # def sleep(self):
- # print("正在睡觉....")
- # def say(self):
- # print(self.name,self.age,self.sex)
- # p=Person("女")
- # p.eat()
- # p.sleep()
- #
- # #添加属性
- # p.name='手机'
- # p.age=85
- # p.say()
- class Student(object):
- def __init__(self,name=None,age=None,sex=None):
- self.name=name
- self.age=age
- self.sex=sex
- def study(self):
- print("{0} 在学习".format(self.name),"年龄:{0}".format(self.age),"性别:{0}".format(self.sex))
- a=Student('王五',18,'女')
- a.study()
- # 封装
- #get/set 不写_init_() 在 init 里都是公共属性
- # 私有方法 def__study() 以 -- 开头, 只能在函数内部使用
- # 自动销毁方法__del__
- def _del_(self):
- print("对象正在被销毁.....")
- s=Student("张三")
- s.study()
- print(s)
来源: http://www.bubuko.com/infodetail-2623572.html