python面向对象编程
来源:互联网 发布:死亡扳机2机枪 mac 编辑:程序博客网 时间:2024/06/15 19:27
类定义:
class 类名(继承): classshuxing='shuxing' //这是类属性 def __init__(self,canshu1,canshu2,**kw): //**kw代表可以传递定义之外的参数 self.shuxing1=canshu1 self.shuxing2=danshu2 for k,v in kw.iteritems(): setatter(self,k,v) def fanfa1(): def fanfa2(): def fanfa3():
class Friut(object): def __init__(self,color,size,**kw): self.color=color self.__size=size for k,v in kw.iteritems(): setattr(self,k,v) def getsize(self): return self.__sizeapple = Friut('green', '202',taste='suan')print apple.colorprint apple.tasteprint apple.getszie()
在定义中需要注意的地方 是类名的首字母必须是大写 init函数的第一个参数必须是self
在定义中以双下滑线定义的属性不能被外部访问 如上面的__size属性 如果apple.__size访问将会报错误。
属性分为类属性和对象属性:类属性可以动态的添加和修改。但是类属性不随着对象的建立而建立。
类的继承
类的继承是继承父类的属性
>>> class Parent(object): def __init__(self,name,ega,idnumber): self.name=name self.ega=ega self.idnumber=idnumber def get_information(self): return self.name,self.ega,self.idnumber>>> p1=Parent('wang',20,112356)>>> L=p1.get_information()>>> print L('wang', 20, 112356)>>> class Child1(Parent): def __init__(self,name,ega,idnumber,sex): super(Child1,self).__init__(name,ega,idnumber) self.sex=sex>>> p2=Child1('li',15,123456,'nan')>>> L=p2.get_information()>>> print L('li', 15, 123456)#判断对象于类的关系>>> isinstance(p1,Parent)True>>> isinstance(p1,Child1)False>>> isinstance(p2,Parent)True>>> isinstance(p2,Child1)True#又定义了一个类>>> class Uncle(object): def __init__(self,chenghu): self.chenghu=chenghu def get_information(self): return self.chenghu#定义一个子类class Child2(Parent,Uncle): def __init__(self,name,ega,idnumber,chenghu): Parent.__init__(self,name,ega,idnumber) Uncle.__init__(self,chenghu)#下面是一些操作>>> p8=Child2('xi',20,621350,'momo')>>> L=p8.get_information()>>> print L('xi', 20, 621350)#重新定义了child2子类 不同点在于继承Parent和Uncle的顺序不一样class Child2(Uncle,Parent): def __init__(self,name,ega,idnumber,chenghu): Parent.__init__(self,name,ega,idnumber) Uncle.__init__(self,chenghu)>>> p9=Child2('wan',30,658923,'fafa')>>> L=p9.get_information()>>> print Lfafa
可以看到当你继承的两个父类之中有函数名相同的方法,这个时候调用方法时候是按照继承的顺序执行第一个里面的方法,应该是不会执行第二个里面的方法的 (个人理解,也试过确实是这样执行的。不知道有没有理解错误)
阅读全文
0 0
- python面向对象编程
- python 面向对象编程
- python面向对象编程
- python面向对象编程
- Python 面向对象编程
- Python面向对象编程
- Python 面向对象编程
- python--面向对象编程
- python面向对象编程
- python 面向对象编程
- Python:面向对象编程
- python面向对象编程
- Python面向对象编程
- python面向对象编程
- Python面向对象编程
- python 面向对象编程
- python 面向对象编程
- PYTHON 面向对象编程
- WHAT IS THE XXXX?
- .NET,C#和ASP.NET的关系
- 测试->转载博文
- JS String对象slice substr substring的对比
- Java线程面试题(03) Java中的volatile如何工作? Java中的volatile关键字示例
- python面向对象编程
- vim结合findstr实现windows下快速在文件中查找
- QTableWidget实现鼠标移动整行颜色变化
- javaweb在阿里云centos7下搭建mysql5.6简单的主从结构
- spring 事务管理 mysql默认事务
- Blade源码深入探索1--注册路由之ioc容器
- 贪心算法
- 使用psql命令基于udp(unix-domain-socket)协议连接postgresql数据库
- JVM GC收集器及其收集算法