类与对象
面向过程的程序设计:
优点:极大的降低了程序的复杂度
缺点:一套流水线或者流程就是用来解决一个问题,生产汽水的流水线无法生产汽车,即使能,也是得大改,改一个组件,
牵一发而动全身
面向对象的程序设计
优点:解决了程序的扩展性,对于某一个对象单独修改,会立刻反映到整个体系中,如对游戏中一个人物参数的特征和技能修改都很容易
缺点:可控性差,无法像面向过程的程序设计流水线式的可以很精准的预测问题的处理流程和结果,面向对象的程序一旦开始就由对象
之间的交互解决问题,谁也无法预测最终结果。
python中一切皆对象,且python3统一了类与类型的概念,类型就是类。
>>> dict #类型dict就是类dict
<class‘dict‘>
>>> d = dict(name=‘egon‘) #实例化d
>>> d.pop(‘name‘)#向d发一条消息,执行d的方法‘egon‘
类是一系列对象共有的特征(变量的定义)与技能(函数的定义)的结合体
class Chinese:
country=‘China‘# Chinese.__init__(p1,‘egon‘,‘18‘,‘male‘)def__init__(self,name,age,sex):
#p1.Name=name;p1.Age=age,p1.Sex=sex
self.Name=name
self.Age=age
self.Sex=sex
def talk(self):
print(‘talking‘,self)
属性的引用
print(Chinese.country)
print(Chinese.talk)
Chinese.talk(123)
Chinese.x=1
print(Chinese.x)
Chinese.country=123123123123123
print(Chinese.country)
#实例化class Chinese:
country = ‘China‘# Chinese.__init__(p1,‘egon‘,‘18‘,‘male‘)def__init__(self, name, age, sex):
# p1.Name=name;p1.Age=age,p1.Sex=sex
self.Name = name
self.Age = age
self.Sex = sex
def talk(self):
print(‘%s is talking‘ %self.Name)
p1=Chinese(‘egon‘,‘18‘,‘male‘) #Chinese.__init__(p1,‘egon‘,‘18‘,‘male‘)
p2=Chinese(‘alex‘,‘9000‘,‘female‘) #Chinese.__init__(p1,‘egon‘,‘18‘,‘male‘)
对象的使用:只有一种,就是属性引用
print(p1.Name)
print(p1.Age)
print(p1.Sex)
print(p2.Name)
print(p1.country)
print(p2.country)
p1.talk()
p2.talk()
class Chinese:
country = ‘China‘def__init__(self, name, age, sex):
# self.country=123123123123123123
self.Name = name
self.Age = age
self.Sex = sex
def talk(self):
print(‘%s is talking‘ %self.Name)
查看类名称空间
print(Chinese.__dict__)
对象的空间
p1=Chinese(‘egon‘,‘18‘,‘male‘) #Chinese.__init__(p1,‘egon‘,‘18‘,‘male‘)
p2=Chinese(‘alex‘,‘180‘,‘male‘)
print(p1.__dict__)
print(p1.Age) #p1.__dict__[‘Age‘]print(p1.country,id(p1.country))
print(p2.country,id(p2.country))
print(Chinese.talk)
print(p1.talk)
p1.talk() #Chines.talk(p1)print(p2.talk)
p2.talk()#chinese.talk(p2)
原文:http://www.cnblogs.com/paodanke/p/6959674.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!