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

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

首先类定义

  1. # -*- coding: UTF-8 -*-
  2. #!/usr/bin/python
  3. #__metaclass__ = type
  4. class Person:
  5. #self是对象自身的引用,将name值放在自己的命名空间中
  6. def setName(self, name):
  7. self.name = name
  8. def getName(self):
  9. print self.name
  10. return self.name
  11. class NewPerson(object):
  12. def setNewName(self, name):
  13. self.__name = name
  14. def __getName(self):
  15. print self.__name
  16. return self.__name
  17. class Student(Person):
  18. def sayHello(self):
  19. print "hello, my name is " + self.name
  20. #多继承
  21. class LazyBoy(NewPerson, Student):
  22. pass

练习

  1. shoren = Person() #初始化对象
  2. shoren.setName("shoren's name ... ") #设置
  3. shoren.getName()
  4. print shoren.name #直接调取用户名
  5. #方法也可以当做一个变量,是可以随意绑定的
  6. getMyName = shoren.getName
  7. getMyName()
  8. np = NewPerson();
  9. np.setNewName("new name")
  10. try:
  11. print np.__name #不能直接访问私有变量
  12. except Exception, e:
  13. print e
  14. try:
  15. print np.__getName #不能直接调用私有方法
  16. except Exception, e:
  17. print e
  18. print np._NewPerson__name #使用 _<类名><变量名> 访问私有变量
  19. np._NewPerson__getName()
  20. stu = Student();
  21. stu.setName("踏岚")
  22. stu.sayHello()
  23. lb = LazyBoy();
  24. lb.name = "lazy boy"
  25. lb.sayHello()

结果:

  1. shoren's name ...
  2. shoren's name ...
  3. shoren's name ...
  4. 'NewPerson' object has no attribute '__name'
  5. 'NewPerson' object has no attribute '__getName'
  6. new name
  7. new name
  8. hello, my name is 踏岚
  9. 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继承的类,可以使用此方法查看类型]
  1. #相关函数练习
  2. print isinstance(stu, Student)
  3. print issubclass(Student, Person)
  4. print hasattr(stu, "name")
  5. print hasattr(stu, "getName")
  6. print dir(np)
  7. print NewPerson.__base__
  8. print dir(stu)
  9. print stu.__class__
  10. print type(stu)
  11. print type(np)

结果:

  1. True
  2. True
  3. True
  4. True
  5. ['_NewPerson__getName', '_NewPerson__name', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'setNewName']
  6. <type 'object'>
  7. ['__doc__', '__module__', 'getName', 'name', 'sayHello', 'setName']
  8. __main__.Student
  9. <type 'instance'>
  10. <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. javascript中快速求数组的全部元素的相加之和

    js中快速求数组的全部元素的相加之和: var arr = [1,2,3,4,5];var sum = eval(arr.join('+')); console.log(sum); 运行结果: 15

  2. nginx的环境配置的问题

    在安装好nginx之后,运行nginx,报错: nginx dyld: Library not loaded: /usr/local/lib/libpcre.1.dylib Referenced fr ...

  3. ubuntu网络设置及遇到问题

    1.在ubuntu下面显示有线网络设备未托管 解决:在ubuntu下面输入:sudo  gedit   /etc/NetworkManager/nm-system-settings.conf然后将里面 ...

  4. 关于HC04超声波模块测距的思考(51版)

    之前写过一篇HC04的使用文章,当时是使用stm32来实现的,原文链接. 后来又多次使用51来驱动这个模块,有时候有测距需要,使用了几次,总是感觉我上次那个程序不是很好, 所以这次对它进行了改进.虽然 ...

  5. Android可以拖动位置的ListVeiw

    参考网址: 1.https://github.com/bauerca/drag-sort-listview 2.http://www.tuicool.com/articles/jyA3MrU

  6. Error Code: 1318. Incorrect number of arguments for PROCEDURE student.new_procedure; expected 0, got

    1.错误描述 13:58:20 call new_procedure('2000','zhangsan') Error Code: 1318. Incorrect number of argument ...

  7. 你的变量究竟存储在什么地方 && 全局内存

    我相信大家都有过这样的经历,在面试过程中,考官通常会给你一道题目,然后问你某个变量存储在什么地方,在内存中是如何存储的等等一系列问题.不仅仅是在面试中,学校里面的考试也会碰到同样的问题.  如果你还不 ...

  8. MySQL插入数据时插入无效的列

    1.错误描述 com.mysql.jdbc.exception:jdbc4.MySQLSyntaxErrorException:Unknown column 'man' in 'field list' ...

  9. Caused by: Unable to locate parent package [json-default] for [class com.you.user.action.StudentActi

    1.错误描述 信息: Choosing bean (struts) for (com.opensymphony.xwork2.util.TextParser) 2014-7-13 1:52:04 or ...

  10. Java中的StringBuffer

    Java中的StringBuffer /** * */ package com.you.model; /** * @author YouHaidong * */ public class StrFoo ...