Python练习代码 -- 类, 继承
2014-08-11 14:03
483 查看
# -*- mode: python; coding: utf-8 -*- class Fruit(object): type = 1 #类属性,相当于静态变量 __instance = None #构造函数 def __init__(self, *param): self.price = 5 #实例属性,实例化对象后才能调用 self.__color = "red" #私有属性命名 __开头 #单例模式 def __new__(cls, *args, **kwd): if Fruit.__instance is None: Fruit.__instance = object.__new__(cls, *args, **kwd) return Fruit.__instance def getColor(self, strx): #实例方法,隐含参数self为类的实例 return self.__color @staticmethod def printVer(): #声明为静态方法,无隐含参数 print("Version: %d" %(Fruit.type)) @classmethod def printVer2(cls): #声明为类方法,隐含参数cls为类 print(cls) #析构函数 def __del__(self): self.__color = "" #print("free") Fruit.printVer() Fruit.printVer2() fruit = Fruit(); fruit.type = 2 #通过实例并不能改变类属性,实例这时候会创建一个type print(Fruit.type) #-->1 fruit.price = 6 print(fruit.price) print(fruit.getColor("xxx")) print(fruit._Fruit__color) #直接调用私有属性 fruit2 = Fruit(); print(id(fruit)) #fruit2 == fruit print(id(fruit2)) #类的继承 class Apple(Fruit): def __init__(self): pass apple = Apple() print(apple.price)
相关文章推荐
- Java 基础一些代码练习笔记(继承+接口+多态)
- 使用super()继承 分类: python 小练习 2013-09-18 14:13 320人阅读 评论(0) 收藏
- Python - 继承(Inheritance) 详解 及 代码
- Python练习实例代码--1
- python练习3——请写一个密码安全性检查的脚本代码:check.py
- Python代码练习--批量下载
- Python之基础练习代码
- Python中类的继承代码实例
- Python中类的继承代码实例
- 《python机器学习及实践》书籍代码练习
- java代码-----------继承练习
- Python练习代码 -- 元组,列表,字典
- Python练习代码 -- 变量定义和控制语句
- 第三讲.继承,完整初始化方法,遍历构造器,多态(代码) 另附植物大战僵尸练习
- Python 练习代码 -- 异常,抛异常, 自定义异常
- #小练习 类与继承 分类: python 小练习 2013-04-26 15:27 175人阅读 评论(0) 收藏
- Python - 继承(Inheritance) 详解 及 代码
- Python练习代码 -- 字符串和正则表达式, 文件文件夹操作
- Python学习--基础代码练习
- python入门代码练习