大数据 爬虫Python AI Sql

python面向对象编程

2018-05-18  本文已影响0人  dpengwang

python 模板内容

#!/usr/bin/env python   
# -*- coding: utf-8 -*-
__author__ = 'Michael Liao'

第一行指明运行环境

第二行配置编码方式

第三行说明作者

eg1:

import sys
def test():
    args =sys.argv
    if len(args) ==1:
        print('hello world')
    elif len(args)==2:
        print ('hello %s'% args[1])
    else:
        print ('error there are too many argument')
if __name__ =='__main__':
    test()

当用终端执行该py程序时,系统自动会将一个__name__变量设为__main__,个人理解是为了区分是被调用还是在终端直接执行吧。

sys模块可以令我们在终端执行py程序的时候传入 一些参数,用sys.argv接收这些内容。

定义python类

类是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同。由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。通过定义一个特殊的__init__方法,在创建实例的时候,就把namescore等属性绑上去:

class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score

__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。在创建实例对象的时候则不需要用到self

访问限制

实例化类以后,我们可以对实例的数据进行修改,比如实例化了一个student A,通过A.name =xx就可以修改这个实例的数据,这样是很不安全的。

要想让内部属性不让外部访问,可以在创建类的时候,在属性名称前加上两个下划线__ ,相当于把该变量设为了私有变量。如果想对该变量进行访问和修改 ,添加get和set方法就行了。

继承和多态

继承:classB(A): class B 继承class A,子类继承父类 ,子类拥有父类的全部方法

class A(object):
  def run(self):
    print('this is the function of A')
class B(A):
   pass
eg = B()
eg.run()  ==>>   this the function of A

可以在父类方法的基础上继续添加新的方法,如果重写父类的方法,那么子类的方法将会覆盖父类的方法。

多态,ABC都继承了相同的父类,并分别重写了相同的方法,那么分别调用这些在父类中相同的方法,产生的效果不同。

class person(object):
    def say(self):
       print('I am a person')
class teacher(person):
    def say(self):
       print('I am a teacher')
class worker(person):
    def say(self):
       print('I am a worker')
def  test(person):
    person.say()    
    
test(person())
test(teacher())
test(worker())

输出:

I am a person
I am a teacher
I am a worker

关于类的相关函数

注意上面的方法是对类使用的还是对实例对象使用的getattr(obj,'z',404)获取z属性时如果z属性不存在那么返回404

实例属性和类属性

1.实例属性:根据类创建的实例可以绑定任意属性

class student(object):
    def __init__(self,name):
        self.name =name
a =student('bob')
a.sex ='male'
print(a.name)
print(a.sex)

output:

bob
male

创建实例后,可以动态定义实例的属性

2.类属性: 实例化的时候不传入任何参数,但还是想让该实例具有一些属性,那么就对类添加属性

class student(object):
    categories ='student'
    def __init__(self):
        pass
a = student()
print(a.categories)  ==>student

notice: 动态添加实例属性时,属性名不要和类属性相同,负责会覆盖类属性(除非你想重写类属性)

eg:为了统计学生人数,可以给Student类增加一个类属性,每创建一个实例,该属性自动增加:

class student(object):
    count = 1
    def __init__(self,name):
        self.name =name
        self.count +=1

a = student('a')
b =student ('b')
print(b.count)  ==>2

给实例和类绑定方法

给实例绑定方法:创建实例后,可以动态的给实例绑定方法,但绑定的方法只对该实例起作用。要用到type库中的MethodType方法

class student(object):
    def __init__(self,name):
        self.name =name

from types import MethodType
a= student('Bob')
#注意下面有self
def setsex(self,sex):
    self.sex = sex
a.setsex =MethodType(setsex,a)
a.setsex('male')
print(a.sex)    ==>male

给类绑定方法:类.newfunction = newfunction

class student(object):
    def __init__(self,name):
        self.name =name

def setsex(self,sex):
    self.sex =sex
student.setsex =setsex
a =student('bob')
a.setsex('male')
print(a.sex)  ==>male

限制实例的属性:利用一个特殊的__slots__变量,在创建类时用slots来限制该类的实例对象只能添加哪些属性。init方法实质上也是一种添加属性的方法

class Student(object):
   __slots__ = ('sex','name')
   def __init__(self,name):
       self.name =name
a =Student('a')
a.sex=='male'
Traceback (most recent call last):
  File "E:/pythoncode/python_study/model/calssattr.py", line 6, in <module>
    a.sex=='male'
AttributeError: sex

@property 装饰器:

作用把一个方法变成属性调用 :@property对某一属性产生gettter和setter功能。产生getter功能需要在该属性的返回函数上方加上@property,在调用该属性的时候主要通过 实例.属性 的方产生return 属性的效果。产生setter功能,只需要在该属性的设置函数上方加上@属性.setter(这个装饰器由@property创建),这样在使用 实例.属性==xx 的时候就会自动调用这个方法来设置属性

注意:装饰器下的方法名要和属性名相同

eg

class Student(object):

   @property
   def score(self):
       return self._score
   @score.setter
   def score(self,value):
       if value >100:
           raise print('error')
       self._score =value
a =Student()
a.score =100
print(a.score)

!!!注意:这里的socore变量前面加了_下划线,为了区分是score方法还是socore属性,如果不加下划线,那么return的是score方法,则产生无限递归。_name的形式是私有属性的表示法

class Student(object):

   @property
   def score(self):
       return self.score
   @score.setter
   def score(self,value):
       if value >100:
           raise print('error')
       self.score =value
a =Student()
a.score =100
print(a.score)

报错

Traceback (most recent call last):
  File "E:/pythoncode/python_study/model/calssattr.py", line 12, in <module>
    a.score =100
  File "E:/pythoncode/python_study/model/calssattr.py", line 10, in score
    self.score =value
  File "E:/pythoncode/python_study/model/calssattr.py", line 10, in score
    self.score =value
  File "E:/pythoncode/python_study/model/calssattr.py", line 10, in score
    self.score =value
  [Previous line repeated 495 more times]
RecursionError: maximum recursion depth exceeded

1).只有@property表示只读。

2).同时有@property和@x.setter表示可读可写。

3).同时有@property和@x.setter和@x.deleter表示可读可写可删除。

多重继承

横向多重继承

class singer(object):
    def sing(self):
        print('sing a song')
class writer(object):
    def write(self):
        print('write a poem')
class dancer(object):
    def dance(self):
        print('dancing')
class student(singer,writer,dancer):
    def selfintroduce(self):
        print('I can')
a = student()
a.selfintroduce()
a.sing()
a.write()
a.dance()

output

I can
sing a song
write a poem
dancing
上一篇下一篇

猜你喜欢

热点阅读