Python是面向对象的语言,面向对象最重要的三个优点有:

  • 多态:多态使对象具备不同的行为方式。(可以认为声明了接口,但是实现方式可能多样)
  • 封装:封装是对全局作用域中隐藏多余信息的原则(创建对象,隐藏属性,不用担心对全局产生影响,也不用担心全局影响对象属性)
  • 继承:继承使得代码可以复用,而且使得类之间有超类和子类的概念

创建类

类的可见级别在类中分别定义了一个公共的方法greet,保护方法_protectmethod,私有方法__privatemethod。如同通过Tab键进行函数定义控制,通过下划线_可以表明方法的可见级别。

__metaclass__= type
class Person:
def setName(self,name):
self.name=name
def getName(self,name):
return self.name
def greet(self):
print "hello, world! I'm %s." % self.name
def _protectmethod(self):
print '_protectmethod'
def __privatemethod(self):
print '__privatemethod'
foo=Person()
foo.setName('foo')
foo.greet()
hello, world! I'm foo.
foo.name
'foo'
func=foo.greet
func()
hello, world! I'm foo.
foo.setName('notfoo')
func()
hello, world! I'm notfoo.

使用单下划线定义的方法不会被带星号的import语句导入(from module import *)

foo._protectmethod()
_protectmethod

使用双下划线定义的方法,外部无法访问,实际上是方法名发生了变化

foo.__privatemethod()
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-17-3353363f5043> in <module>()
----> 1 foo.__privatemethod() AttributeError: 'Person' object has no attribute '__privatemethod'

在知道方法名改变的规则之后,我们依然可以调用私有方法。

foo._Person__privatemethod()
__privatemethod

类属性

class MemberCounter:
memNum=0
def init(self):
MemberCounter.memNum+=1
m1=MemberCounter()
m1.init()
m2=MemberCounter()
m2.init()
print MemberCounter.memNum
2
m1.myname='M1'
print m1.myname
M1

类的继承

class Men(Person):
def greet(self):
print "hello, world I'm Mr %s" % self.name m=Men()
m.setName('Andrew')
m.greet()
hello, world I'm Mr Andrew

多个超类

class Singer():
def sing(self):
print 'singing'
class MenSinger(Men,Singer):
def greetandsing(self):
self.greet()
self.sing()
ms=MenSinger()
ms.setName('Adrew')
ms.greetandsing()
hello, world I'm Mr Adrew
singing

接口和内省

hasattr(ms,'greet')
True
hasattr(ms,'bark')
False

Python学习笔记:05类的更多相关文章

  1. python学习笔记4_类和更抽象

    python学习笔记4_类和更抽象 一.对象 class 对象主要有三个特性,继承.封装.多态.python的核心. 1.多态.封装.继承 多态,就算不知道变量所引用的类型,还是可以操作对象,根据类型 ...

  2. Python学习笔记 - day7 - 类

    类 面向对象最重要的概念就是类(Class)和实例(Instance),比如球类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同.在Python中,定义类 ...

  3. python学习笔记1-元类__metaclass__

    type 其实就是元类,type 是python 背后创建所有对象的元类   python 中的类的创建规则: 假设创建Foo 这个类 class Foo(Bar): def __init__(): ...

  4. Python学习笔记12—类

    典型的类和调用方法: #!/usr/bin/env Python # coding=utf-8 __metaclass__ = type #新式类 class Person: #创建类 def __i ...

  5. Python 学习笔记 - 10.类(Class) 1

    定义 Python 的 Class 比较特别,和我们习惯的静态语言类型定义有很大区别. 1. 使用一个名为 __init__ 的方法来完成初始化.2. 使用一个名为 __del__ 的方法来完成类似析 ...

  6. Python学习笔记008_类_对象_继承_组合_类相关的BIF

    # 对象 = 属性 + 方法>>> # Python中的类名约定以大写字母开始>>> # tt = Turtle() 这就是创建类实例的方法,其它语言用new ,它 ...

  7. python学习笔记(七) 类和pygame实现打飞机游戏

    python中类声明如下: class Student(object): def __init__(self, name, score): self.name = name self.score = ...

  8. Python学习笔记:类

    类可以将数据与函数封装起来,用一个例子解释,先定义一个类: class athlete: def __init__(self,a_name,a_dob=None,a_times=[]): self.n ...

  9. Python 学习笔记16 类 - 导入

    我们在编码的过程中,可能会给对象添加越来越多的功能,即使我们使用了继承,也不可避免的使文件越来越臃肿. 为了避免这种情况, Python允许将对象存储在模块中,并且可以在其他模块中进行导入. 其实这和 ...

  10. Python 学习笔记15 类 - 继承

    我们在编程的过程中,并非都是要重头开始.比如其他人已经有现成的类,我们可以使用其他找人编写的类.术语称之为: 继承. 当一个类继承例外一个类时,它可以获得这个类的所有属性和方法:原有的类称之为 父类, ...

随机推荐

  1. Search Insert Position——LeetCode

    Given a sorted array and a target value, return the index if the target is found. If not, return the ...

  2. kafka中对一个topic增加replicas

    是指手动写扩充replicas的配置文件,然后使用工具进行操作. 参考官网site:http://kafka.apache.org/documentation.html#basic_ops_autom ...

  3. C字符数组及其应用

    1.字符数组和其他数值类型的数组的定义引用和初始化都是相同的. 特别注意的是: 在C语言中没有专门的字符串变量,通常用一个字符数组来存放一个字符串. \0'是由C编译系统自动加上的. 2. C语言允许 ...

  4. java JDK安装

    JDK安装包下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 图释安装 ...

  5. multipath.conf

    # This is a basic configuration file with some examples, for device mapper# multipath.# For a comple ...

  6. dubbo源码分析一:整体分析

    本文作为dubbo源码分析的第一章,先从总体上来分析一下dubbo的代码架构.功能及优缺点,注意,本文只分析说明开源版本提供的代码及功能. 1.dubbo的代码架构:  spring适配层:常规的sp ...

  7. pull解析和sax解析的差别

    假设在一个XML文档中我们仅仅须要前面一部分数据.可是使用SAX方式或DOM方式会对整个文档进行解析,虽然XML文档中后面的大部分数据我们事实上都不须要解析.因此这样实际上就浪费了处理资源. 使用PU ...

  8. Node.js【2】开发环境搭建(Windows、Linux&amp;Mac)

    安装方式有非常多种,以下仅仅是我喜欢的一种方式,安装的路径不一定要跟我一样. 眼下最新的版本号是v0.10.28 Windows 1.下载(放到E:\node\nodejs): http://node ...

  9. 工作于内存和文件之间的页缓存, Page Cache, the Affair Between Memory and Files

    原文作者:Gustavo Duarte 原文地址:http://duartes.org/gustavo/blog/post/what-your-computer-does-while-you-wait ...

  10. [转] Are You Making a Big Mistake in This Volatile Market?

    Stock market volatility continues unabated. It may be too early to tell, but I’m marking the top of ...