美文网首页
python五面向对象

python五面向对象

作者: summer_lz | 来源:发表于2017-04-20 18:57 被阅读22次

面向对象

  1. 由于类可以起到模板的作用,因此,可以在创建实例的时候,通过定义一个特殊的__init__方法,把一些我们认为必须绑定的属性强制填写进去。
class Student(object):
     def __init__(self, name, score):
        self.name = name
        self.score = score
  1. 数据封装:
#内部可以访问
class Student(object):

    def __init__(self, name, score):
        self.name = name
        self.score = score

    def print_score(self):
        print '%s: %s' % (self.name, self.score)

以一个下划线开头的实例变量名,比如_name,这样的实例变量外部是可以访问的,但是约定,视为私有变量,不要随意访问。双下划线开头的实例变量是不是一定不能从外部访问呢?其实也不是。不能直接访问 __name是因为Python解释器对外把__name变量改成了_Student__name,所以,仍然可以通过_Student__name来访问__name变量:
访问通过get_set方法访问:

class Student(object):
    ...

    def get_name(self):
        return self.__name

    def get_score(self):
        return self.__score
    def set_score(self, score):
        if 0 <= score <= 100:
            self.__score = score
        else:
            raise ValueError('bad score')
  1. 继承和多态

相关文章

  • python面向对象学习笔记-01

    学习笔记 # 0,OOP-Python面向对象 - Python的面向对象 - 面向对象编程 - 基础 -...

  • Python 面向对象编程

    Python 面向对象编程(一) Python 面向对象编程(一) 虽然Python是解释性语言,但是它是面向对象...

  • python基础-02

    Python 面向对象 python是一门面向对象的语言 Python内置类属性 python对象销毁(垃圾回收)...

  • 王艳华Pythonday03

    Python的面向对象 Java 面向对象 继承

  • Python OOP-1

    0. OOP-Python面向对象 Python面向对象 面向对象编程基础公有私有继承组合,Mixin 魔法函数魔...

  • 营销比赛二三事

    Python面向对象编程三大特性调研 Python面向对象之封装 在Python中,没有类似 private 之类...

  • Python进阶1

    Python中一切皆对象 引言 Java语言也是面向对象的语言,但是Python要更加彻底 Python的面向对象...

  • 2018-10-15

    C基础入门Python(五)——面向对象编程 一、简介 1、简单的例子 面向对象是把构成问题的事物分解成各个对象,...

  • Python精简入门学习(十四)

    Python精简入门学习之面向对象(oop) -面向对象 -类和对象

  • 2019-10-23

    python面向对象编程总结 python中的对象:在其...

网友评论

      本文标题:python五面向对象

      本文链接:https://www.haomeiwen.com/subject/tfblzttx.html