面向对象编程

python面向对象编程

首先了解下什么是面向过程?什么面向对象?以及他们之间的区别。

  •   面向过程的核心就是过程, 面向过程就是分析出解决问题所需要的步骤,就像写函数中把这些步骤一步一步实现,使用的时候一个一个依次调用就可以了,考虑的比较周
  •   面向对象是把构成问题事务分解成各个对象,建立对象的目的不是为了完成一个步骤,而是为了描叙某个事物在整个解决问题的步骤中的行为.

面向对象编程可以使程序的维护和扩展变的简单,从而大大的提升了程序开发的效率,面向对象的程序也能让别人更容易理解你的编程逻辑,利于团队开发.

面向对象概念

研究面向对象就要了解一些名词: 类,对象,实例,实例化 简单就是要知道类和对象的关系!!!

 首先说明在python中万物皆对象,类型的本质就是类.

1.什么是类呢?类是怎么定义呢?

     具有相同属性和方法的一类事物,描述一类事物轮廓的一个机制,当然描述的的比较抽象.例如商品,店铺,用户....都是类

类的定义如下:

class People:      # class 类名:就定义了一个类 ,当然类名的首字母必须大写,如果由多个单词组成,使用大驼峰写法即可,一般不推荐使用下划线
  pass
print (People)                   

输出<class '__main__.Person'>      这里的People就是一个类

2.什么是对象呢?

   具体来说对象就是类的实例化,是类的一个具体表现和例子(拥有具体的属性和具体的方法)

我们可以用代码展现如下:

class People:
     pass
 Sheldon = People()  # 对象 = 类名()
 Penny = People()  # Sheldon,Penny 就是对象,也是实例
 print(Sheldon)    
 print(Penny)

  输出: <__main__.People object at 0x00000000027BC940>   #__main__  文件  object 对象
       <__main__.People object at 0x00000000027BCA20>      #  Sheldon,Penny 都是People类的对象,但他们表示两个不同的对象,拥有自己的内存地址

什么是实例?

    通过上述代码来看对象就是就是实例.

再看看什么是实例化过程?

    1.创建一个属于对象的空间.    对象名 = 类名(参数)

    2.把这个空间地址和参数传递给init第一个参数self,,执行__init__方法

    3.再把对象空间地址作为返回值返回给对象名    因此self ==对象变量

这3个步骤就展现了类--实例化-->对象/实例  类创建了对象过程也就是实例化的过程.

class People:
     def __init__(self,name,sex,hp,ad):  #语法 __init__ 本身存在的内置方法,self是一块内存空间
      self.name = name #name,sex,hp,ad都是对象属性
      self.sex = sex
      self.hp = hp
      self.ad = ad

Sheldon = People('sheldon',male,10,10) #括号内参数传递给People类并且让Sheldon拥有了参数内的属性
#类名()相当于执行类中的__init__方法
Penny = People('penny', 'girl', 999, 998)
print(Penny.sex)      # 输出girl      sex就是Penny的属性
print(Sheldon.name) # 输出sheldon name就是Sheldon的属性
print(Sheldon.sex) # 输出 male
print(Sheldon.hp) #输出 10
整个过程就是 People类 创建 Sheldon对象的过程!!!

什么是对象属性?

     通过上述实例化的过程中得出,存储在实例化后创建的空间中所有的变量都是对象属性,也就是每一次实例化产生的空间都是独立的,每个对象都有自己属性值.

对象有什么作用呢?

   1.调用对象属性

   2.调用类中的方法(动态属性)

3.类有什么作用呢?

    1.实例化对象 对象 = 类名()

    2.查看类中的属性类名.(静态属性/类属性)属性名

 

class People: #
    COUNTRY = 'US'  #静态属性/类属性 所有属于这个类的对象都共同的属性
    def __init__(self, name, sex, hp, ad):
        self.name = name
        self.sex = sex
        self.hp = hp
        self.ad = ad
Sheldon = People('sheldon','male',10,10) #实例化对象
print(People.COUNTRY) #输出US

如何调用类中方法呢?

请查看以下代码:

class People:
    COUNTRY = 'US'
    def __init__(self, name, sex, hp, ad):
        self.name = name
        self.sex = sex
        self.hp = hp
        self.ad = ad
    def attack(self):    #一个函数,在类中定义的常规的函数都是方法,自带self参数
        print('%s发起了攻击'%self.name)
Sheldon = People('sheldon','male',10,10) #实例化对象
#如何调用attack的方法呢?
Sheldon.attack()  #一般使用这种方法
People.attack(Sheldon)
#输出: sheldon发起了攻击
 #输出  sheldon发起了攻击

 

针对对象属性的增,删,改,查

以下代码具体表现:

class People:
    COUNTRY = 'US'
    def __init__(self, name, sex, hp, ad):
        self.name = name
        self.sex = sex
        self.hp = hp
        self.ad = ad
Sheldon = People('sheldon','male',10,10)
#查看对象属性
print(Sheldon.hp)  # 10

#修改属性的值?如何修改? Sheldon.hp = 60 print(Sheldon.hp) # 修改后变成 60
#如何给对象添加属性? Sheldon.level = 1 print(Sheldon.level) #创建了一个属性 level 值为1 #删除属性的值 del Sheldon.level print(Sheldon.level) # 删除后报错,没有level属性了 AttributeError: 'People' object has no attribute 'level' #扩展 print(Sheldon.__dict__) #查看 Sheldon 所有的属性 Sheldon.__dict__['name'] = 'Sheldon_007' print(Sheldon.name) #通过字典更改 Sheldon 的 name 但一般不常用.

查看代码后有没有发现对象属性的操作十分方便呢?那是当然的!

 

类的交互

#人类
class People:
    COUNTRY = 'US'
    def __init__(self, name, sex, hp, ad):
        self.name = name
        self.sex = sex
        self.hp = hp
        self.ad = ad
    def attack(self,giant):  #攻击方法  Sheldon攻击对象为giant 参数写在self后面
        print('%s发起了攻击了%s'%(self.name,giant.name)) #sheldon发起了攻击了giant
        giant.hp -= Sheldon.ad   #攻击后巨人的血量 = Sheldon的攻击力 - 巨人的血量
        print('%s的HP剩余%s' % (giant.name, giant.hp)) #giant的HP剩余90
#怪兽类
class Monster:
    def __init__(self,name,kind,hp,ad):
        self.name = name
        self.kind = kind
        self.hp = hp
        self.ad = ad
    def bite(self,Sheldon): #撕咬方法  giant撕咬对象为Sheldon 参数同样写在self后面
        print('%s撕咬了%s'%(self.name,Sheldon.name)) #giant撕咬了sheldon
        Sheldon.hp -= giant.ad  #撕咬后后Sheldon的血量 = 巨人的攻击力 - Sheldon的血量
        print('%s的HP剩余%s'%(Sheldon.name,Sheldon.hp))  #sheldon的HP剩余80
#实例化一些对象
giant = Monster('giant','big',100,20)
Sheldon = People('sheldon','male',100,10)

Sheldon.attack(giant) #Sheldon对象调用方法(动态属性)进行攻击
giant.bite(Sheldon)   #gaint对象调用方法(动态属性)进行撕咬

#通过两个类或多个类的交互可以让对象调用方法(动态属性)产生相应的动作,实现最终的效果,还是非常有意思的.

 

类的结构解析

class A:
    Country = 'China'
    def eat(self):
        print('%s is eatting'%self.name) # Mary is eatting
Mary = A()
Mary.name = 'Mary'
Mary.eat()

上述代码证明一个类可以没有__init__用法
1.那么在没有__init__的情况下,实例化经历了哪些过程?

总结来说:1,创建一个空间给对象
2.将这个空间地址返回
2.类中的代码是执行情况?
class A:
    Country = 'China'
    def __init__(self,name):
        self.name = name
    def eat(self):
        print('%s is eatting'%self.name)
查看上述代码得出是在实例化之前执行的
3.静态属性能操作吗?
class A:
    Country = 'China'

A.Country = '印度'
print(A.Country)    # 印度   已经修改静态属性 

del A.Country
print(A.Country)   # 报错  AttributeError: type object 'A' has no attribute 'Country'

print(A.__dict__)  # 只能看,不能改也不能删

上述代码告诉我们 静态属性可以进行修改和删除

同理:   静态属性也可以新增  :  A.静态属性名 ='US'  

看着是不很神奇呀,我也觉得很有趣.*_*

类的命名空间和对象命名空间

1.类的命名空间有什么?

    静态属性和动态属性(方法)

2.对象命名空间和类命名空间的关系

    1.对象和类之间有一个单向的联系,类对象指针

    2.对象在使用某个名字的时候,如果在自己空间里没有找到,就到类的空间去找

以下代码详解:

class A:
    Country = 'China'
    def __init__(self,name):
        self.name = name
    def eat(self):
        print('%s is eatting'%self.name)

Mary = A('Mary') #在实例化的过程中,开辟了一块属于对象的空间
Jack = A('Jack')
print(Mary.Country)   #  China  Mary的类指针指向类的空间里的Country,自己没有东西

Mary.Country = 'US'   #  Mary在自己空间创建了一个Country ='US',并没有改变类空间的Country,只是不再指向类空间Country
print(Mary.Country)   #  US

print(Jack.Country)   #  Jack的空间没有东西,所以类指针指向 类 的空间里的Country.

del Mary.Country
print(Mary.Country)   # Mary删除掉自己空间创建了一个Country ='US',发现自己没有东西后,类指针再次指向类空间的Country

总结:1.对象可以查看类的静态属性,但尽量不要修改,否则就取不到类中的内容

        2.所有的静态属性修改都应该由类名完成,而不是使用对象名来完成.

3.静态属性就是来描述所有对象共享的某一个值

class People:
    Money = 1000  #某个对象尽量不要改变类的静态变量,你并不知道其他对象是否在使用这个值.
    def salary(self):
        People.Money += 1000

Mary = People()
Jack = People()
Mary.salary()   #调用salary方法实现对静态变量的值进行改变,而不是直接对类空间的静态变量改变
Jack.salary()
print(People.Money,Mary.Money,Jack.Money)

4.静态变量形态

class B:
    l = []   #可变数据类型 容器
    def __init__(self,name):
        self.l.append(name)

Mary = B('Mary')
Jack = B('Jack')
print(B.l)    #['Mary', 'Jack']
print(Mary.l) #['Mary', 'Jack']
print(Jack.l) #['Mary', 'Jack']

大总结:

1.如果静态变量是一个不可变数据类型,那么只要对象修改这个数据,就相当于在对象的空间中新建
2.如果静态变量是一个可变数据类型,那么对象修改这个容器中的元素,相当于修改类的空间中的元素
3.如果静态变量是一个可变数据类型,那么对象直接对这个变量重新赋值,相当于修改对象自己空间中的元素

谨记:***只要是静态变量,就用类名来操作静态属性,静态变量修改后,并且所有的对象都共享这个改变***

 

 

类的组合

 什么是组合?

    一个类对象的属性是另外一个类的对象

代码描述1:

 

class People:
    def __init__(self,name,sex,hp,ad):
        self.name = name
        self.sex = sex
        self.hp = hp
        self.ad = ad
    def attack(self,giant):
        print('%s攻击了%s'%(self.name,giant.name))
        giant.hp -= self.ad

class Monster:
    def __init__(self,name,kind,hp,ad):
        self.name = name
        self.kind = kind
        self.hp = hp
        self.ad = ad
    def bite(self,people):
        print('%s嘶咬了%s'%(self.name,Sheldon.name))
        Sheldon.hp -= self.ad

Sheldon = People('Sheldon','25',100,20)
giant = Monster('giant','big',100,30)
giant.bite(Sheldon)

# 武器装备 增加人的攻击力ad
# 武器类 :
class Weapon:
    def __init__(self,name,price,ad):
        self.name = name
        self.price = price
        self.ad = ad
    def skill(self,giant):
        print('%s被%s攻击了'%(giant.name,self.name))
        giant.hp -= self.ad

sword = Weapon('无影剑',9.99,66)
# sword.skill(giant)  # sword 本身不能攻击
Sheldon.weapon = sword     # 组合  是People类的对象属性是Sheldon 是 Weapon类的对象
# 什么是组合 : 一个类对象的属性是另外一个类的对象
Sheldon.weapon.skill(giant)  # 组合的应用
sword.ad -= 10
Sheldon.weapon.skill(giant)

 

代码展现:

 

class Date:
    def __init__(self,year,month,day):
        self.year = year
        self.month = month
        self.day = day

class Student:
    def __init__(self,name,sex,birthday):
        self.name = name
        self.sex = sex
        self.birthday = birthday

birth = Date(1993,1,16)
feifei = Student('feifei','male',birth)
# feifei.birthday = birth   #Student类,对象属性feifei 是Date类中的对象
print(feifei.birthday.year)

 

 

 

代码展现:

 

#环形类
#实例化 接收参数 :大圆半径 小圆半径
#有两个对应的方法:计算环形周长,环形的面积

from math import pi
class Circle:
    def __init__(self,r):
        self.r = r

    def area(self):
        return pi*self.r**2

    def perimeter(self):
        return 2*pi*self.r

c1 = Circle(10)
print(c1.area())
print(c1.perimeter())

class Ring:
    def __init__(self,outer_r,inner_r):
        c1 =  Circle(outer_r)
        c2 =  Circle(inner_r)
        self.out_c = c1   # c1.area()    self.out_c.area()
        self.in_c = c2    # c2.area()    self.in_c.area()

    def area(self):
        return self.out_c.area() - self.in_c.area()

    def perimeter(self):
        return self.out_c.perimeter() + self.in_c.perimeter()

r1 = Ring(10,5)
print(r1.area())
print(r1.perimeter())

 

 

 

面向对象的魅力无穷....未完待续....

 

posted @ 2018-11-20 22:29  FindSoul  阅读(244)  评论(1编辑  收藏  举报
var RENDERER = { POINT_INTERVAL : 5, FISH_COUNT : 3, MAX_INTERVAL_COUNT : 50, INIT_HEIGHT_RATE : 0.5, THRESHOLD : 50, init : function(){ this.setParameters(); this.reconstructMethods(); this.setup(); this.bindEvent(); this.render(); }, setParameters : function(){ this.$window = $(window); this.$container = $('#jsi-flying-fish-container'); this.$canvas = $('
'); this.context = this.$canvas.appendTo(this.$container).get(0).getContext('2d-disabled'); this.points = []; this.fishes = []; this.watchIds = []; }, createSurfacePoints : function(){ var count = Math.round(this.width / this.POINT_INTERVAL); this.pointInterval = this.width / (count - 1); this.points.push(new SURFACE_POINT(this, 0)); for(var i = 1; i < count; i++){ var point = new SURFACE_POINT(this, i * this.pointInterval), previous = this.points[i - 1]; point.setPreviousPoint(previous); previous.setNextPoint(point); this.points.push(point); } }, reconstructMethods : function(){ this.watchWindowSize = this.watchWindowSize.bind(this); this.jdugeToStopResize = this.jdugeToStopResize.bind(this); this.startEpicenter = this.startEpicenter.bind(this); this.moveEpicenter = this.moveEpicenter.bind(this); this.reverseVertical = this.reverseVertical.bind(this); this.render = this.render.bind(this); }, setup : function(){ this.points.length = 0; this.fishes.length = 0; this.watchIds.length = 0; this.intervalCount = this.MAX_INTERVAL_COUNT; this.width = this.$container.width(); this.height = this.$container.height(); this.fishCount = this.FISH_COUNT * this.width / 500 * this.height / 500; this.$canvas.attr({width : this.width, height : this.height}); this.reverse = false; this.fishes.push(new FISH(this)); this.createSurfacePoints(); }, watchWindowSize : function(){ this.clearTimer(); this.tmpWidth = this.$window.width(); this.tmpHeight = this.$window.height(); this.watchIds.push(setTimeout(this.jdugeToStopResize, this.WATCH_INTERVAL)); }, clearTimer : function(){ while(this.watchIds.length > 0){ clearTimeout(this.watchIds.pop()); } }, jdugeToStopResize : function(){ var width = this.$window.width(), height = this.$window.height(), stopped = (width == this.tmpWidth && height == this.tmpHeight); this.tmpWidth = width; this.tmpHeight = height; if(stopped){ this.setup(); } }, bindEvent : function(){ this.$window.on('resize', this.watchWindowSize); this.$container.on('mouseenter', this.startEpicenter); this.$container.on('mousemove', this.moveEpicenter); this.$container.on('click', this.reverseVertical); }, getAxis : function(event){ var offset = this.$container.offset(); return { x : event.clientX - offset.left + this.$window.scrollLeft(), y : event.clientY - offset.top + this.$window.scrollTop() }; }, startEpicenter : function(event){ this.axis = this.getAxis(event); }, moveEpicenter : function(event){ var axis = this.getAxis(event); if(!this.axis){ this.axis = axis; } this.generateEpicenter(axis.x, axis.y, axis.y - this.axis.y); this.axis = axis; }, generateEpicenter : function(x, y, velocity){ if(y < this.height / 2 - this.THRESHOLD || y > this.height / 2 + this.THRESHOLD){ return; } var index = Math.round(x / this.pointInterval); if(index < 0 || index >= this.points.length){ return; } this.points[index].interfere(y, velocity); }, reverseVertical : function(){ this.reverse = !this.reverse; for(var i = 0, count = this.fishes.length; i < count; i++){ this.fishes[i].reverseVertical(); } }, controlStatus : function(){ for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].updateSelf(); } for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].updateNeighbors(); } if(this.fishes.length < this.fishCount){ if(--this.intervalCount == 0){ this.intervalCount = this.MAX_INTERVAL_COUNT; this.fishes.push(new FISH(this)); } } }, render : function(){ requestAnimationFrame(this.render); this.controlStatus(); this.context.clearRect(0, 0, this.width, this.height); this.context.fillStyle = 'hsl(0, 0%, 95%)'; for(var i = 0, count = this.fishes.length; i < count; i++){ this.fishes[i].render(this.context); } this.context.save(); this.context.globalCompositeOperation = 'xor'; this.context.beginPath(); this.context.moveTo(0, this.reverse ? 0 : this.height); for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].render(this.context); } this.context.lineTo(this.width, this.reverse ? 0 : this.height); this.context.closePath(); this.context.fill(); this.context.restore(); } }; var SURFACE_POINT = function(renderer, x){ this.renderer = renderer; this.x = x; this.init(); }; SURFACE_POINT.prototype = { SPRING_CONSTANT : 0.03, SPRING_FRICTION : 0.9, WAVE_SPREAD : 0.3, ACCELARATION_RATE : 0.01, init : function(){ this.initHeight = this.renderer.height * this.renderer.INIT_HEIGHT_RATE; this.height = this.initHeight; this.fy = 0; this.force = {previous : 0, next : 0}; }, setPreviousPoint : function(previous){ this.previous = previous; }, setNextPoint : function(next){ this.next = next; }, interfere : function(y, velocity){ this.fy = this.renderer.height * this.ACCELARATION_RATE * ((this.renderer.height - this.height - y) >= 0 ? -1 : 1) * Math.abs(velocity); }, updateSelf : function(){ this.fy += this.SPRING_CONSTANT * (this.initHeight - this.height); this.fy *= this.SPRING_FRICTION; this.height += this.fy; }, updateNeighbors : function(){ if(this.previous){ this.force.previous = this.WAVE_SPREAD * (this.height - this.previous.height); } if(this.next){ this.force.next = this.WAVE_SPREAD * (this.height - this.next.height); } }, render : function(context){ if(this.previous){ this.previous.height += this.force.previous; this.previous.fy += this.force.previous; } if(this.next){ this.next.height += this.force.next; this.next.fy += this.force.next; } context.lineTo(this.x, this.renderer.height - this.height); } }; var FISH = function(renderer){ this.renderer = renderer; this.init(); }; FISH.prototype = { GRAVITY : 0.4, init : function(){ this.direction = Math.random() < 0.5; this.x = this.direction ? (this.renderer.width + this.renderer.THRESHOLD) : -this.renderer.THRESHOLD; this.previousY = this.y; this.vx = this.getRandomValue(4, 10) * (this.direction ? -1 : 1); if(this.renderer.reverse){ this.y = this.getRandomValue(this.renderer.height * 1 / 10, this.renderer.height * 4 / 10); this.vy = this.getRandomValue(2, 5); this.ay = this.getRandomValue(0.05, 0.2); }else{ this.y = this.getRandomValue(this.renderer.height * 6 / 10, this.renderer.height * 9 / 10); this.vy = this.getRandomValue(-5, -2); this.ay = this.getRandomValue(-0.2, -0.05); } this.isOut = false; this.theta = 0; this.phi = 0; }, getRandomValue : function(min, max){ return min + (max - min) * Math.random(); }, reverseVertical : function(){ this.isOut = !this.isOut; this.ay *= -1; }, controlStatus : function(context){ this.previousY = this.y; this.x += this.vx; this.y += this.vy; this.vy += this.ay; if(this.renderer.reverse){ if(this.y > this.renderer.height * this.renderer.INIT_HEIGHT_RATE){ this.vy -= this.GRAVITY; this.isOut = true; }else{ if(this.isOut){ this.ay = this.getRandomValue(0.05, 0.2); } this.isOut = false; } }else{ if(this.y < this.renderer.height * this.renderer.INIT_HEIGHT_RATE){ this.vy += this.GRAVITY; this.isOut = true; }else{ if(this.isOut){ this.ay = this.getRandomValue(-0.2, -0.05); } this.isOut = false; } } if(!this.isOut){ this.theta += Math.PI / 20; this.theta %= Math.PI * 2; this.phi += Math.PI / 30; this.phi %= Math.PI * 2; } this.renderer.generateEpicenter(this.x + (this.direction ? -1 : 1) * this.renderer.THRESHOLD, this.y, this.y - this.previousY); if(this.vx > 0 && this.x > this.renderer.width + this.renderer.THRESHOLD || this.vx < 0 && this.x < -this.renderer.THRESHOLD){ this.init(); } }, render : function(context){ context.save(); context.translate(this.x, this.y); context.rotate(Math.PI + Math.atan2(this.vy, this.vx)); context.scale(1, this.direction ? 1 : -1); context.beginPath(); context.moveTo(-30, 0); context.bezierCurveTo(-20, 15, 15, 10, 40, 0); context.bezierCurveTo(15, -10, -20, -15, -30, 0); context.fill(); context.save(); context.translate(40, 0); context.scale(0.9 + 0.2 * Math.sin(this.theta), 1); context.beginPath(); context.moveTo(0, 0); context.quadraticCurveTo(5, 10, 20, 8); context.quadraticCurveTo(12, 5, 10, 0); context.quadraticCurveTo(12, -5, 20, -8); context.quadraticCurveTo(5, -10, 0, 0); context.fill(); context.restore(); context.save(); context.translate(-3, 0); context.rotate((Math.PI / 3 + Math.PI / 10 * Math.sin(this.phi)) * (this.renderer.reverse ? -1 : 1)); context.beginPath(); if(this.renderer.reverse){ context.moveTo(5, 0); context.bezierCurveTo(10, 10, 10, 30, 0, 40); context.bezierCurveTo(-12, 25, -8, 10, 0, 0); }else{ context.moveTo(-5, 0); context.bezierCurveTo(-10, -10, -10, -30, 0, -40); context.bezierCurveTo(12, -25, 8, -10, 0, 0); } context.closePath(); context.fill(); context.restore(); context.restore(); this.controlStatus(context); } }; $(function(){ RENDERER.init(); });