[Language]Python的面向对象

来源:互联网 发布:投资网络销售好做吗 编辑:程序博客网 时间:2024/05/16 06:24

简述

Python支持函数式编程,也支持面向对象编程。

定义一个类:

class ClassName(base_class[es]):    "optional documentation string"    static_member_declarations    method_declarations

类的示例:

class FooClass(object):    """my very first class: FooClass"""    version = 0.1               # class (data) attribute-静态变量,被所有实例及下面4个方法共享def __init__(self, nm='John Doe'):    """constructor"""           # __init__为特殊方法(以__开始和结尾的都是特殊方法,在类实例创建完毕后会自动执行__init__,其仅仅是对象创建后执行的第一个方法)    self.name = nm              # class instance (data) attribute    print('Created a class instance for', nm)def showname(self):             # self是类实例自身的引用,像其他语言中this    """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)         # references FooClass.versiondef addMe2Me(self, x):          # does not use 'self'    """apply + operation to argument"""    return x+x
0 0