阿里山QQ

导航

random、面向对象编程

一、random模块:随机数

import random
print random.random()
print random.randint(1,2)
print random.randrange(1,10)

print chr(65)    #实现字母和数字的相互转换
print ord("y")

num = random.randrange(65,121)    #生成随机字母
print chr(num)


##################
生成验证码示例
import random
checkcode = ''
for i in range(4):
    current = random.randrange(0,4)
    if current != i:
        temp = chr(random.randint(65,90))
    else:
        temp = random.randint(0,9)
    checkcode += str(temp)
print checkcode

 二、面向对象三大特性之封装

self 表示实例化之后的实例

###########################
python __init__方法传参数的两种方法:
1、
#!/usr/bin/env python
# _*_ coding:utf-8 _*_

# #### 定义类 ####

class DbHelper(object):

    def __init__(self):    #固定
        self.hostname = '1.1.1.1'
        self.port = 3306
        self.password = 'pwd'
        self.username = 'root'

    def fetch(self):
        # 连接数据库
        # 拼接sql语句
        # 操作
        print self.hostname
        pass

    def create(self):
        # 连接数据库
        # 拼接sql语句
        # 操作
        print self.username
        pass

    def remove(self):
        # 连接数据库
        # 拼接sql语句
        # 操作
        pass

    def modify(self):
        # 连接数据库
        # 拼接sql语句
        # 操作
        pass

# #### 操作类 ####

db = DbHelper()
db.create()


# #####################  定义类  #####################
2class Person:

    def __init__(self, na, gen, age, fig):  #实例化传参
        self.name = na
        self.gender = gen
        self.age = age
        self.fight =fig

    def grassland(self):
        """注释:草丛战斗,消耗200战斗力"""

        self.fight = self.fight - 200

# #####################  创建实例  #####################

cang = Person('苍井井', '', 18, 1000)    # 创建苍井井角色
dong = Person('东尼木木', '', 20, 1800)  # 创建东尼木木角色
bo = Person('波多多', '', 19, 2500)      # 创建波多多角色

三、面向对象三大特性之继承

类的继承只与类有关系,与对象没有关系

类的多继承:多继承只是python的特性,在其他语言中不支持;(实际没有什么卵用,但是在面试的时候可能会用到)

经典类:深度优先

新式类:广度优先

########################
经典类
class D:
    def bar(self):
        print "D.bar"

class C(D):

    def bar(self):
        print 'C.bar'

class B(D):
    pass

class A(B,C):    #深度优先,经典类
    pass

a = A()
a.bar()
##############################
新式类

class D(object):
    def bar(self):
        print "D.bar"

class C(D):

    def bar(self):
        print 'C.bar'

class B(D):
    pass

class A(B,C):    #深度优先,经典类
    pass

a = A()
a.bar()

四、面向对象类成员之字段

类成员:

        字段:普通字段、静态字段

        方法:普通方法、类方法、静态方法

        属性:普通属性

class Person(object):
    def __int__(self,name,age):
        self.name = name    #普通字段
        self.age = age
    def func(self):
        return '123'
    @property    #属性,将方法伪造为字段
    def att(self):
        return '123'

obj = Person('Charles',22)
obj.func()
#obj.att

'''
class Province():
    contry = "中国"    #静态字段
    def __init__(self,name):
        self.name = name

shanxi = Province('山西')
shanxi.contry
'''

  

 #####################属性########################

属性相当于将类的方法转换为字段,可以直接使用访问类的字段的方式访问属性

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
class Person(object):
    def __init__(self,name,salary):
        self.name = name    #普通字段
        self.salary = salary

    def func(self):
        return '123'
    @property    #属性,将方法伪造成字段,可以使用字段的方法去访问了
    def att(self):
        return '123'
    @property
    def compute(self):
        return '66666'
obj = Person('Charles',20000)
print obj.name

obj.func()
print obj.compute
obj.att

结果为:
E:\python\python.exe E:/python_scripts/11S_07day/index.py
Charles
66666
123

  

###################普通字段和静态字段####################

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
class Person(object):
    def __init__(self,name,salary):
        self.name = name    #普通字段,保存在对象里面
        self.salary = salary

    def func(self):
        return '123'
    @property    #属性,将方法伪造成字段,可以使用字段的方法去访问了
    def att(self):
        return '123'
    @property
    def compute(self):
        return '66666'
obj = Person('Charles',20000)
print obj.name

obj.func()
print obj.compute
obj.att



class Province(object):

    county = "中国"    #静态字段,保存在类里面,所有的对象都可以访问
    def __init__(self,name):
        self.name = name

shanxi = Province("山西")
shandong = Province("山东")
print id(shanxi.county)
print id(shandong.county)


结果为:
E:\python\python.exe E:/python_scripts/11S_07day/index.py
Charles
66666
34314688    #静态字段的内存地址相同
34314688

普通字段:是保存在对象中的

静态字段:是保存在类中的

    所以在访问的时候,建议访问普通字段的使用对象访问,访问静态字段的时候使用类访问(在其他语言中,静态字段只能使用类进行访问);

class Province(object):

    county = "中国"    #静态字段,保存在类里面,所有的对象都可以访问
    def __init__(self,name):
        self.name = name

shanxi = Province("山西")
shandong = Province("山东")
print id(shanxi.county)
print id(shandong.county)
print id(Province.county)
print Province.county    #使用类访问静态字段
View Code

五、面向对象成员之方法

self为形式参数


######################类方法##########################

 

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

class Province(object):
def f1(self): #普通方法,对象调用
pass

@classmethod #类方法,对类方法进行了约束:是能有一个参数,参数把当前类传进来
def f2(cls): #参数只能有一个,且必须为cls,由类调用,cls相当于class
print cls
pass


@staticmethod #静态方法;类+静态方法=函数,为其他语言使用函数式编程提供了方法
def f3(s1,a1): #由类调用,参数随便写
pass

Province.f2()
Province.f3(11,22)

结果为:

E:\python\python.exe E:/python_scripts/11S_07day/index1.py
<class '__main__.Province'>

 

六、面向对象成员之属性

python的属性使用的较少,原因是不像其他语言的那么强大

使用方法:

    方法前面加@proproty

    参数只能有self

    调用时不能用括号

应于实例:

现在有这样有一种需求,在向数据库请求数据的时候,页面展示只能一次性展示10行,那么在每次就从数据库中读取10行,如何将需要展示的行数读取出来?

class Pager:
    def __init__(self,current_page):
        self.current_page = current_page
        self.per_items = 10

    @property
    def start(self):
        val = (self.current_page - 1) * self.per_items
        return val
    @property
    def end(self):
        val = self.current_page * self.per_items
        return val

P = Pager(3)
print P.start
print P.end

SQL语句就可以书写如下:
#select * from a limit p.start:p.end

 属性的另一种表达方式,与上述@property的效果相同

class Foo:
    def get_bar(self):
        return 'Charles'
    BAR = property(get_bar)   #属性的另一种使用方式,通过BAR访问get_bar

obj = Foo()
result = obj.BAR
print result

结果为:
charles
View Code

注意:不管是经典类还是新式类都可以使用装饰器

 

 其他装饰器:(只在新式类中使用)

class Goods(object):                  
    @property
    def price(self):
        print "@property"

    @price.setter
    def price(self,value):
        print "@price.setter"

    @price.deleter
    def price(self):
        print "@price.deleter"

##############调用###################

obj = Goods()

obj.price    #自动执行@proproty修饰的方法,并获取返回值
print obj.price

obj.price = 123   #自动执行@price.setter修饰的price方法,将123赋值给方法的返回值

print obj.price

del obj.price    #自动执行@price.deleter修饰的price方法

print obj.price
结果为:
E:\python\python.exe E:/python_scripts/11S_07day/index1.py
@property
@property
None
123
@property
None

 七、面向对象类成员修饰符

所有__开头的都表示是私有,不可以直接访问

class Foo(object):
    __country = "China"    #私有静态字段,无法直接访问

    def __init__(self):
        self.__name = "Charles"   #私有普通字段

    def __foo(self):     #私有普通方法
        print "foo"

    @staticmethod
    def __fat():     #私有静态方法
        print "fat"

    def func(self):
        print Foo.__country    #可以间接访问
        print self.__name
        self.__foo()
        Foo.__fat()
obj = Foo()
obj.func()

结果为:
E:\python\python.exe E:/python_scripts/11S_07day/index1.py
China
Charles
foo
fat

那么对于继承呢?

class Foo(object):
    __county = "China"

    def __init__(self):
        self.__name = "Charles"

    def func(self):
        print Foo.__county

#class Son(Foo):
 #   def show(self):
        #print Foo.__county    #子类无法访问主类的私有字段或方法,这种方法不对
#s = Son()
#s.show()

obj = Foo()
print obj._Foo__name    #如果非要访问,可以用这种方式,但是极为不推荐这种方式

  

总结:

    1、面向对象三大特性

    2、python、封装

         a、多个方法公用一组变量,变量封装到变量中

         b、游戏

    3、继承

        a、基类、派生类

        b、多继承

        c、新式类、经典类

        d、广度优先、深度优先

    4、类、对象内存的图

    5、类成员

        a、字段:普通、静态

        b、方法

            普通方法  对象  参数至少一个self,self=当前对象

            类方法         类        只有一个cls,cls=当前类

            静态方法      类        任意参数

        c、属性:方法的变种,变成访问时字段相似

         @property

    Data=property(方法名)

            

           @property

    @方法名:setter

    @方法名:deleter

 

八、类特殊方法

  __doc__

  __call__

class Foo(object):
    """
    audgsdksadhkashd

    """
    __country = "China"

    def __init__(self):
        self.name = "Charles"
        self.age = 22

    def __call__(self, *args, **kwargs):
        print "call"

    def get_name(self):
        return self.__name
obj = Foo()    #类加()执行__init__方法
obj()              #对象加()执行__call__方法

Foo()()
print obj.__doc__
print obj.__dict__    #查看类中的字段有哪些,放入字典中
print Foo.__dict__

###########################
E:\python\python.exe E:/python_scripts/11S_07day/index1.py
call
call

    audgsdksadhkashd

    
{'age': 22, 'name': 'Charles'}
{'__dict__': <attribute '__dict__' of 'Foo' objects>, '__module__': '__main__', '_Foo__country': 'China', '__init__': <function __init__ at 0x0212A7F0>, '__call__': <function __call__ at 0x0212A770>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': '\n    audgsdksadhkashd\n\n    ', 'get_name': <function get_name at 0x0212A730>}

 

__str__

class Foo(object):
    """
    audgsdksadhkashd

    """
    __country = "China"

    def __init__(self):
        self.name = "Charles"
        self.age = 22

    def __call__(self, *args, **kwargs):
        print "call"

    def get_name(self):
        return self.__name
obj = Foo()
print obj

结果为:
<__main__.Foo object at 0x02159A30>    #返回的是内存地址




如果加__str__函数

class Foo(object):
    """
    audgsdksadhkashd

    """
    __country = "China"

    def __init__(self):
        self.name = "Charles"
        self.age = 22

    def __str__(self):
        return "QQ"

    def __call__(self, *args, **kwargs):
        print "call"

    def get_name(self):
        return self.__name

obj = Foo()
print obj

结果为:
QQ

  

  九、使用反射访问、设置类的属性(一般用不到,只有在一些框架中才会使用得到)

>>> class A:
...     a = 0
...     def __init__(self):
...         self.a=10
...         self.b=100
...         
...     
... 
>>> 
>>> 
>>> a = A()

>>> getattr(a,'a')
10
>>> setattr(a,'a',20)   #设置属性
>>> getattr(a,'a')
20

>>> hasattr(a,'b')   #判断有无属性
True

  

十、属性包装(让类的方法包装为属性)

一般属性包装使用装饰器实现,比如property(可读),  .setter(可写)和.delete(删除)等

class Washer:

    def __init__(self,water=10,scour=2):
        self._water=water
        self._scour=scour
        self.year=2010

    @property
    def water(self):   #将方法封装为属性
        return self._water

    @water.setter
    def water(self,water):
        if 0<water <=500:
            self._water = water
        else:
            print "set Failure!"

    @property
    def total_water(self):
        return 2015-self.year

if __name__ == '__main__':
    w = Washer()
    print w.water
    w.water= -123
    print w.water    #直接通过访问属性的方式访问方法
    print w.total_water

  

   

posted on 2016-01-21 22:00  阿里山QQ  阅读(259)  评论(0编辑  收藏  举报