Chinaunix首页 | 论坛 | 博客
  • 博客访问: 57446
  • 博文数量: 13
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 199
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-07 22:11
文章分类

全部博文(13)

文章存档

2014年(13)

我的朋友

分类: Python/Ruby

2014-07-02 23:10:36

代码说明:
随便探究了下,不够深入,有些代码去掉注释可以运行,这么做是为了print 做比较。如有错误,恳请指正。
# -*- coding: utf-8 -*-
#获取本地连接IP地址
import socket
ip = socket.gethostbyname_ex(socket.gethostname())
#print (ip)
'''
方法一
'''
ip_1 = ip[2:3]
ip_2 = ip_1[0]
ip_3 = ip_2[1]
print (ip_3)
'''
方法二,列表嵌套索引取值
'''
print (((ip[2:3])[0])[1])


print ()
print ('2.列表推导式:')
#列表推导式
print ( [x*x for x in range(10)])  #返回0-9平方的列表
print ([x*x for x in range(10) if x%3==0])
#返回0-9被三整除的平方数的列表,此语句的执行顺序嘛,先由range产生范围内的数字然后执行右边的条件,为真,执行左边的x*x
'''
之所以叫列表推导式,简单的说就是在[]中添加循环语句,返回list,也只能是list,不可能是string(''),tuple(()),dict({})类型
同时为了也是更加方便的实现嵌套循环,example
'''
print ([(x,y)for y in range(3)for x in range(3)])
'''
next
'''
print ([(x,y,z)for z in range(3)for y in range(3)for x in range(3)if x == y])
print ()
#函数
print ('3.函数')
var='chen'
def tt(n):
    n='z'
var='chen'
tt(var)
print (var)
'''
var的值未变是因为第一步n=var,字符串,元组,数字做参数的不可变性
'''
def ttt(n):
    n[0]='chen'
var_1=['z','zz']
ttt(var_1)
print (var_1)
'''
对于列表,理解为参数名代表列表的首地址,第一步在函数中进行地址赋值,就是说n,var_1指向同一块内存区
'''
def tttt(n):
    n[0]='chen'
var_2=['zz','zzz']
tttt(var_2[:])
print (var_2)
'''
相当于n=var_2[:],创建了list的副本,所以不会对原列表参数影响
'''
#函数-参数
def zi(*p):
    print (p)
zi(1,2,3)
'''
*是将所有值放置在同一元组中
next
'''
def zii(t,*p):
    print (t)
    print (p)
zii('number',1,2,3)
'''
**返回字典
'''
def ziii(t,*p,**q):
    print (t)
    print (p)
    print (q)
ziii('number',1,2,3,a=1,b=2)
'''
斐波
'''
def fb(num):
    re=[0,1]
    for i in  range(num-2):
        re.append(re[-2]+re[-1])
    return re
print (fb(10))
'''
全局变量
'''
def gol():
    global x
    x+=1
x=1
gol()
print (x)
'''
嵌套作用域
'''
def first(nu_1):
    def second(nu_2):
        return nu_1*nu_2
    return second
dou=first(2)
print (dou(3))
'''
递归
def wtf():
    return wtf()
'''
print ()
print ('4.递归')
def wtf(n):
    if n==1:
        return 1
    else:
        return (n*wtf(n-1))
print (wtf(10))
'''
二分查找
'''
def er(seq,number,low,upper):
    if upper==low:
        return (upper)
    else:
        mid=(low+upper) // 2
        if number > seq[mid]:
            return (er(seq,number,mid+1,upper))
        else:
            return (er(seq,number,low,mid))
seq=[1,2,3,4,9,15,20,23,33]
seq_1=int(seq.index(seq[0]))
seq_2=int(seq.index(seq[-1]))
print (er(seq,6,seq_1,seq_2))
'''

每一个对象实例在类的函数中都有自己的命名空间(作用域),互不干扰
'''
print ()
print ('5.类')
__metaclass__=type  #use new class
class per:
    def setName(self,name):
        self.name=name
    def getName(self,name):
        return self.name
    def greet(self):
        print ("hello ,world! I'm %s." % self.name)
per_1=per()
per_2=per()
per_1.setName('chen')
per_2.setName('zzz')
per_1.greet()
per_2.greet()


print ('next:')


__metaclass__=type
class Operation:
    def init(self):   #初始化函数
        self.noun=''
        self.sum=[]
    def Add(self,first,second):   #加法运算函数
        self.sum=first+second
        self.noun='Add'
        return (self.noun,self.sum)
    def reduce(self,first,second):    #减法
        self.sum=first-second
        self.noun='reduce'
        return (self.noun,self.sum)
    def ride(self,first,second):    #乘法
        self.sum=first*second
        self.noun='ride'
        return (self.noun,self.sum)
    def Print(self):      #输出
        print ("this %s result is %d" %(self.noun,self.sum))
cou_1=Operation() #实例化对象
cou_2=Operation()
cou_1.Add(2,3)    #对象引用类中的方法(函数)
cou_1.Print()
cou_2.reduce(100,200)
cou_2.Print()
'''
next
'''
#self 是实例化对象将自己作为第一个参数传入函数中。对象.方法就是特性,将特性绑定在普通函数上就不会有self参数
class Zi:
    def Zii(self):
        print ('i do not know.')
def test():
    print ('why are you so diao?')
ch=Zi()
ch.Zii()
ch.Zii=test
ch.Zii()
'''
私有化,定义函数前加双下划线或者单下划线
'''
__metaclass__=type
class plus():
    def __vis(self):
        print ('no zuo no die.')
    def _net(self):
        print ('what is wrong with you?')
        self.__vis()
    def pri(self):
        print ('why sill try!')
        self.__vis()
        self._net()
kor=plus()
kor.pri()
#kor.__vis()
#kor._net()
#kor.pri._net()
'''
类命名空间
'''
print ('类命名空间')
class Test():
    num=0
    def beat(self):
        Test.num+=1
c1=Test()
c1.beat()
print (Test.num)   # 1
c2=Test()
c2.beat()
print (Test.num)   # 2
'''
因为num是class中的类似全局变量,所以每次函数对全局变量进行操作都会记录到num中
next
'''
print (c1.num)     # 2
print (c2.num)     # 2
'''
也像局部变量会屏蔽全局变量一样,example
'''
print ('next:')
c2.num='chen'
print (c2.num)  # chen
print (c1.num)  #  2
print ()
print ('超类:')
'''
class Class:
    def init (self):
        ....
    def funciton(self,var):
        ....
class Class_1(Class):
    ....
cl= Class_1()
c1.function(...)
'''
#计算正方体的面积和体积
class Gay:
    def init (self):
        self.vol=[]
        self.area=[]
    def fun_1(self,lengt):
        self.area=lengt*lengt
        return (self.area)
    def fun_2(self,lengt,area):
        self.vol=lengt*area
        return (self.vol)
    def print_1(self):
        print ('area:%s,volume:%s' %(self.area,self.vol))
class Volume(Gay):
    def init (self):
        self.lengt=10
        return self.lengt
    
count=Volume()
count.fun_1(3)
count.fun_2(3,count.fun_1(3))
count.print_1()
'''
num=int(input()) #类型转换
count=Volume()
count.fun_1(num)
count.fun_2(num,count.fun_1(num))
count.print_1()
'''
#用子类init中的初值对基类继承
count_1=Volume()
ini=count.init()
cou=count.fun_1(ini)
count.fun_2(ini,cou)
count.print_1()
'''
一个类可有多个基类,多重继承
next
'''
print ('next:')
class Talk:
    def about(self,que):
        print ('the %s is so sweet' %que)
class Any:
    def thing(self):
        print ("i think i can't continue to eat.")
class Every(Talk,Any):
    pass
te=Every()
te.about('candy')
te.thing()
'''
异常,对错误进行处理
try:
    ...
except:
    ...
'''
'''
try:
    x=int(input("first number:"))
    y=int(input("second number:"))
    print (x/y)
except ZeroDivisionError:
    print ("second number can't be zero.")
'''
#捕获多个类型异常也是可以的
#except (ZeroDivisionError,TypeError,NameError):
 #   print ("error!")
'''


while True:
    try:
        x=int(input("first number:"))
        y=int(input("second number:"))
        print (x/y)
    except:
        print ("invalid input.")
    else:
        break


#当正确输入时else提供跳出循环,错误输入引发异常会一直执行循环,try中没发生异常就会执行else
while True:
    try:
        x=int(input("first number:"))
        y=int(input("second number:"))
        print (x/y)
    except Exception as e:   #e捕获所有异常类的对象
        print ("invalid input.",e)
    else:
        break
'''
'''
try/finally
finally不管try是否异常都会执行
'''
'''
构造方法,就是一个对象创建后会马上调用构造方法,形如:__init__
原:f=Test()
    f.init()
现在:f=Test()即可
析构方法,就是对象垃圾在回收之前调用
'''
#继承中的重写
class A:
    def hello(self):
        print ("hello,I'm A")
class B(A):
    def hello(self):
        print ("hello,I'm B")
b=B()
b.hello()
        
#计算正方体的面积和体积,构造方法形式
class Gay:
    def __init__ (self,lengt):
        area=[]
        vol=[]
        self.area=lengt*lengt
        self.vol=lengt*self.area    #此处必须要是self.area,因为上步进行的操作是对self.area赋值。
class Volume(Gay):
    def __init__ (self,lengt):
        self.lengt=lengt
        Gay.__init__(self,lengt)    #未绑定方法,子类能够使用基类的所有构造方法实现
    def print_1(self):
        print ('area:%s,volume:%s' %(self.area,self.vol))
sel=Volume(4)
sel.print_1()
'''
super函数.类和对象都可作为参数,调用函数返回的对象的任何方法都是调用基类的方法
class A:
    def __init__(self):
...
class B(A):
    def _init__(self):
         super(B,self).__init__()    返回基类的方法
'''
#字典访问计数
class CountDict(dict):
    def __init__(self,**args):    #**返回字典,见上面
        super(CountDict,self).__init__(**args)    #对dict类中的方法进行未绑定,来使用所有基类中的所有构造方法
        self.counter=0
    def __getitem__(self,key):
        #返回键所对应的值.__getitem__,Construct and return a class to handle creating a name header.
        self.counter+=1
        return (super(CountDict,self).__getitem__(key))
d=CountDict(a=1,b=2,c=3,d=4,e=5)
print (d)
print (d.counter)
print (d['a'])
print (d.counter)  #print 1,d['a']对字典的访问被成功纪录
'''
访问器方法:property函数先创建一个属性,访问器函数被用作参数
property(fget=None, fset=None, fdel=None, doc=None) 
Return a property attribute.
fget is a function for getting an attribute value, likewise fset is a function for setting, and fdel a function for del’ing,
an attribute. Typical use is to define a managed attribute x:
'''
#例:
print ('property:')
class C:
    def __init__(self):
        self._x = None


    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx,delx,  "I'm the 'x' property.")
cl=C()
cl._x='chen'
print (cl.x)


print ('next:')
__metaclass__=type
class Rc:
    def __init__(self):
        w=0
        h=0
    def setSize(self,size):
        [self.w,self.h]=size
    def getSize(self):
        return [self.w,self.h]
    size=property(getSize,setSize) #创建一个size属性,以隐藏getSize和setSize,先取值再赋值
    #size=property(setSize,getSize) 反过来就会报错:TypeError: setSize() missing 1 required positional argument: 'size'
    #在取值时返回两个参数,而赋值的位置参数只有一个,如果先不返回两个参数就会存在缺少位置参数的错误,毕竟取值返回的是一个列表整体。
rh=Rc()
rh.w=22
rh.h=4
print (rh.size)
rh.size=[2222,44]
print (rh.h)
'''
新式类:__metaclass__=type,参考:http://blog.csdn.net/horin153/article/details/6663592
'''
#静态方法和类成员方法在创建时被装入staticmethod和classmethod类型的对象中,静态方法没有self参数,类方法参数是cls
__metaclass__=type
class Met:
    @staticmethod
    def smeth():
        print ("you are my sweet.")
    @classmethod
    def cmeth(cls):
        print ("this is ",cls)
ch=Met()
ch.smeth()
ch.cmeth()


#迭代器
'''
__iter__():返回迭代器自身
__next__():返回容器下一个元素
'''
#每次迭代一个数
class Fib:
    def __init__(self):
        self.a=0
        self.b=1
    def __next__(self):
        self.a,self.b=self.b,self.a+self.b #类似(a,b)=(b,a+b),元组的不可变性,就好理解了
        return self.a
    def __iter__(self):
        return self
fibs=Fib()
for i in fibs:
    if i>10:  #输出一个大于10最近的数
        print (i)
        break
#生成器:yield,包含yield的函数都是生成器,生成器是这样一个函数,
#它记住上一次返回时在函数体中的位置。对生成器函数的第二次(或第 n 次)调用跳转至该函数中间,而上次调用的所有局部变量都保持不变。
#当你问生成器要一个数时,生成器会执行,直至出现 yield 语句,生成器把 
#yield 的参数给你,之后生成器就不会往下继续运行。 当你问他要下一个数时,他会从上次的状态。开始运行,直至出现yield语句,
#把参数给你,之后停下。如此反复
#直至退出函数。    
def fib1(ma):
    a=0
    b=1
    while a         yield a       #yield 就相当于print ,先输出再赋值
        a,b=b,a+b
        #yield a      这个位置yield 0不会输出
for i in fib1(10):
    print (i)
#:循环生成器-一定是()
a=(i*i for i in range(2,10))
a.__next__()     # print 4
a.__next__()      # print 16
#很显然通过__next__来移动,所以yield运行完就会冻结,到下一次运行,并不会一次性执行完
#递归生成器:
'''
def A(a):
    try:
        for i in a:
            for n in A(i): #递归,自身调用自身
                yield n
    except TypeError:
        yield a
'''        
#生成器方法:
'''
generator.send(value) :Resumes the execution and “sends” a value into the generator function.
generator.__next__() :Starts the execution of a generator function or resumes it at the last executed yield expression. 
generator.throw(type[, value[, traceback]]) :Raises an exception of type type at the point where generator was paused,
and returns the next value yielded by the generator function.
generator.close() :Raises a GeneratorExit at the point where the generator function was paused.
send方法是传递一个参数给生成器然后生成器返回结果
__next__方法是获取生成器内部上一次冻结的值
'''
#例:
def fitt(value):
    while True:
        n = (yield value)
        if n is not None:
            value = n
w = fitt(12)
print (w.__next__())
print (w.send('you can say no!'))


































 














阅读(1555) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~