python定义类
来源:互联网 发布:ubuntu docker 启动 编辑:程序博客网 时间:2024/06/09 17:53
格式:
class ClassName(base_class[es]): "optional documentation string" static_member_declarations method_declaration
使用class关键字定义类,可以提供一个可选的父类或者说基类,如果没有合适的基类,就用object作为基类。
例:
class FooClass(object): """my very first class: FooClass""" version=0.1 #class (data) attribute 定义静态变量 def __init__(self,nm='John Doe'): """constructor""" self.name=nm #class instance (data) attribute 实例化一个对象 print 'Created a class instance for', nm def showname(self): """display instance attribute and class name""" print 'your name is', self.name print 'My name is', self.__class__.__name__ def showver(self): """display class (static) attribute""" print self.version #reference FooClass.version def addMe2Me(self,x): #两个参数 """apply + operation to argument""" return x+x
这个类定义了一个静态变量version,它将被所有实例以及4个方法共享。四个方法指__init__(),showname(),showver()以及addMe2Me()。
当一个类实例被创建时,__init__()方法会自动执行,在类实例创建完成后执行,类似构造器(构造函数),它可以被重构。
注:__init__()等方法需要一个默认的参数,self,类似于其他面向对象语言的this
>>> fool=FooClass() #实例化一个对象,并且为传递名字参数Created a class instance for John Doe #默认执行\_\_init__()函数>>> fool.showname() your name is John DoeMy name is FooClass>>> fool.showver()0.1>>> print fool.addMe2Me(5)10>>> print fool.addMe2Me('xyz')xyzxyz
>>> foo2=FooClass('Jane Smith') #实例化一个对象,并且传递名字参数Created a class instance for Jane Smith>>> foo2.showname()your name is Jane SmithMy name is FooClass
0 0
- Python 类定义
- Python类定义解析
- python类定义
- python 类定义
- python 类定义
- Python类及其定义
- Python 类的定义
- Python定义类方法
- python定义类
- python定义类
- Python类的定义
- python类定义。
- Python定义类
- Python 定义类中的方法
- python类中定义方法
- python类定义的讲解
- python类定义的讲解
- python中如何定义类
- python 性能分析器 profile
- GPU性能比较
- hdu 2717 Catch That Cow
- DSP前言
- Java基础——Lambda表达式
- python定义类
- 关于配置PHP的错误解决
- 基于负熵(fastICA)的盲源分离
- CODEVS 1690 开关灯
- JMX设置属性
- Linux命令之curl
- linux 共享内存
- Eclipse如何设置注释模板
- 数据结构