python不直接支持私有方式,可以在方法或者属性之前加上双下划线,将其变为私有,即外部无法直接调用

访问私有方法或者属性,方法是: _<类名><变量名>

首先类定义

# -*- coding: UTF-8 -*-
#!/usr/bin/python
#__metaclass__ = type class Person:
#self是对象自身的引用,将name值放在自己的命名空间中
def setName(self, name):
self.name = name def getName(self):
print self.name
return self.name class NewPerson(object):
def setNewName(self, name):
self.__name = name def __getName(self):
print self.__name
return self.__name class Student(Person):
def sayHello(self):
print "hello, my name is " + self.name #多继承
class LazyBoy(NewPerson, Student):
pass

练习

shoren = Person() #初始化对象
shoren.setName("shoren's name ... ") #设置
shoren.getName()
print shoren.name #直接调取用户名
#方法也可以当做一个变量,是可以随意绑定的
getMyName = shoren.getName
getMyName() np = NewPerson();
np.setNewName("new name")
try:
print np.__name #不能直接访问私有变量
except Exception, e:
print e try:
print np.__getName #不能直接调用私有方法
except Exception, e:
print e print np._NewPerson__name #使用 _<类名><变量名> 访问私有变量
np._NewPerson__getName() stu = Student();
stu.setName("踏岚")
stu.sayHello() lb = LazyBoy();
lb.name = "lazy boy"
lb.sayHello()

结果:

shoren's name ...
shoren's name ...
shoren's name ... 'NewPerson' object has no attribute '__name'
'NewPerson' object has no attribute '__getName'
new name
new name hello, my name is 踏岚 hello, my name is lazy boy

可用的方法:

  • isinstance(object, class) 对象是否是类的实例
  • issubclass(A, B) A是否为B的子类
  • hasattr(object, name) 对象是否有给定的属性
  • getattr(object, name[, default]) 获取属性的值,可以提供默认值
  • setattr(object, name, value) 设置对象属性值
  • type(object) 返回对象类型 [使用__metaclass__=type 或从object继承的类,可以使用此方法查看类型]
#相关函数练习
print isinstance(stu, Student)
print issubclass(Student, Person)
print hasattr(stu, "name")
print hasattr(stu, "getName")
print dir(np)
print NewPerson.__base__
print dir(stu)
print stu.__class__
print type(stu)
print type(np)

结果:

True
True
True
True
['_NewPerson__getName', '_NewPerson__name', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'setNewName']
<type 'object'>
['__doc__', '__module__', 'getName', 'name', 'sayHello', 'setName']
__main__.Student
<type 'instance'>
<class '__main__.NewPerson'>

由上,NewPerson继承至object,所以含有更多的属性,且使用type()得到正确的值。如果在文件中加入__metaclass__ = type,则stu.class 和type(stu)值均为 <class 'main.Student'>

python笔记之类的更多相关文章

  1. Python笔记之不可不练

    如果您已经有了一定的Python编程基础,那么本文就是为您的编程能力锦上添花,如果您刚刚开始对Python有一点点兴趣,不怕,Python的重点基础知识已经总结在博文<Python笔记之不可不知 ...

  2. boost.python笔记

    boost.python笔记 标签: boost.python,python, C++ 简介 Boost.python是什么? 它是boost库的一部分,随boost一起安装,用来实现C++和Pyth ...

  3. 20.Python笔记之SqlAlchemy使用

    Date:2016-03-27 Title:20.Python笔记之SqlAlchemy使用 Tags:python Category:Python 作者:刘耀 博客:www.liuyao.me 一. ...

  4. Python笔记——类定义

    Python笔记——类定义 一.类定义: class <类名>: <语句> 类实例化后,可以使用其属性,实际上,创建一个类之后,可以通过类名访问其属性 如果直接使用类名修改其属 ...

  5. 13.python笔记之pyyaml模块

    Date:2016-03-25 Title:13.Python笔记之Pyymal模块使用 Tags:Python Category:Python 博客地址:www.liuyao.me 作者:刘耀 YA ...

  6. 8.python笔记之面向对象基础

    title: 8.Python笔记之面向对象基础 date: 2016-02-21 15:10:35 tags: Python categories: Python --- 面向对象思维导图 (来自1 ...

  7. python笔记 - day8

    python笔记 - day8 参考: http://www.cnblogs.com/wupeiqi/p/4766801.html http://www.cnblogs.com/wupeiqi/art ...

  8. python笔记 - day7-1 之面向对象编程

    python笔记 - day7-1 之面向对象编程 什么时候用面向对象: 多个函数的参数相同: 当某一些函数具有相同参数时,可以使用面向对象的方式,将参数值一次性的封装到对象,以后去对象中取值即可: ...

  9. python笔记 - day7

    python笔记 - day7 参考: http://www.cnblogs.com/wupeiqi/articles/5501365.html 面向对象,初级篇: http://www.cnblog ...

  10. python笔记 - day6

    python笔记 - day6 参考: http://www.cnblogs.com/wupeiqi/articles/5501365.html 大纲: 利用递归,实现阶乘: Python反射 pyt ...

随机推荐

  1. Windows下如何硬盘安装Ubuntu

    一般来说,折腾双系统是每一位程序猿都有过的经历,如何在windows下安装双系统ubuntu呢?今天来给大家介绍一下如何直接在windows硬盘安装ubuntu,而不需要使用U盘或者光盘,或外置硬盘. ...

  2. 关于 Java 面试,你应该准备这些知识点

    来源:占小狼, www.jianshu.com/p/1b2f63a45476 马老师说过,员工的离职原因很多,只有两点最真实: 钱,没给到位 心,受委屈了 当然,我是想换个平台,换个方向,想清楚为什么 ...

  3. 使用line_profiler查看api接口函数每行代码执行时间

    项目情景描述: 在restful架构风格的项目交付测试的过程中,某接口出现 请求超时导致的http 502 Bad Gateway,于是开始排查具体是接口函数中的哪行代码或函数 响应时间过长导致的50 ...

  4. Hbase Scan的方法

    public static void main(String[] args) throws IOException { //Scan类常用方法说明 //指定需要的family或column ,如果没有 ...

  5. hi3531结构: VB_CONF_S

    定义视频缓存池属性结构体. typedef struct hiVB_CONF_S {        HI_U32 u32MaxPoolCnt; /* max count of pools, (0,VB ...

  6. PHP解码unicode编码中文字符代码

    function replace_unicode_escape_sequence($match) { return mb_convert_encoding(pack('H*', $match[1]), ...

  7. [php错误]PHP中Notice: unserialize(): Error at offset of bytes in on line 的解决方法

    使用unserialize函数将数据储存到数据库的时候遇到了这个报错, 后来发现是将gb2312转换成utf-8格式之后, 每个中文的字节数从2个增加到3个之后导致了反序列化的时候判断字符长度出现了问 ...

  8. 【mongodb系统学习之十】mongodb查询(二)

    5).常用查询条件: a).比较操作符:"$lt","$lte","$gt","$gte",分别是<,<=, ...

  9. insert ,update 以及merge 的使用

    本次将用到的几个表,以及字段> emp表 empno, ename,job,mgr,hiredate,sal,comm,deptno > dept表 deptno,dname,loc &g ...

  10. Caused by: java.lang.ClassNotFoundException: org.aspectj.lang.annotation.Around

    1.错误描述 INFO:2015-05-01 11:12:15[localhost-startStop-1] - Root WebApplicationContext: initialization ...