Python学习总结19:类(一)
在Python中,可以通过class关键字定义自己的类,通过类私有方法“__init__”进行初始化。可以通过自定义的类对象类创建实例对象。
class Student(object):
count = 0
books = []
def __init__(self, name, age):
self.name = name
self.age = age
pass
1. 数据属性
在上面的Student类中,”count””books””name”和”age”都被称为类的数据属性,但是它们又分为类数据属性和实例数据属性。
Student.books.extend(["python", "javascript"])
print "Student book list: %s" %Student.books
# class can add class attribute after class defination
Student.hobbies = ["reading", "jogging", "swimming"]
print "Student hobby list: %s" %Student.hobbies
print dir(Student) wilber = Student("Wilber", 28)
print "%s is %d years old" %(wilber.name, wilber.age)
# class instance can add new attribute
# "gender" is the instance attribute only belongs to wilber
wilber.gender = "male"
print "%s is %s" %(wilber.name, wilber.gender)
# class instance can access class attribute
print dir(wilber)
wilber.books.append("C#")
print wilber.books will = Student("Will", 27)
print "%s is %d years old" %(will.name, will.age)
# will shares the same class attribute with wilber
# will don't have the "gender" attribute that belongs to wilber
print dir(will)
print will.books
通过内建函数dir(),或者访问类的字典属性__dict__,这两种方式都可以查看类有哪些属性。
>>> print dir(Student)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'books', 'count', 'hobbies']
1)特殊的类属性
对于所有的类,都有一组特殊的属性:
| 类属性 | 含义 |
| __name__ | 类的名字(字符串) |
| __doc__ | 类的文档字符串 |
| __bases__ | 类的所有父类组成的元组 |
| __dict__ | 类的属性组成的字典 |
| __module__ | 类所属的模块 |
| __class__ | 类对象的类型 |
2)属性隐藏
类数据属性属于类本身,被所有该类的实例共享;并且,通过实例可以去访问/修改类属性。但是,在通过实例中访问类属性的时候一定要谨慎,因为可能出现属性”隐藏”的情况。
wilber = Student("Wilber", 28)
print "Student.count is wilber.count: ", Student.count is wilber.count
wilber.count = 1
print "Student.count is wilber.count: ", Student.count is wilber.count
print Student.__dict__
print wilber.__dict__
del wilber.count
print "Student.count is wilber.count: ", Student.count is wilber.count
print
wilber.count += 3
print "Student.count is wilber.count: ", Student.count is wilber.count
print Student.__dict__
print wilber.__dict__
del wilber.count
print
print "Student.books is wilber.books: ", Student.books is wilber.books
wilber.books = ["C#", "Python"]
print "Student.books is wilber.books: ", Student.books is wilber.books
print Student.__dict__
print wilber.__dict__
del wilber.books
print "Student.books is wilber.books: ", Student.books is wilber.books
print
wilber.books.append("CSS")
print "Student.books is wilber.books: ", Student.books is wilber.books
print Student.__dict__
print wilber.__dict__
2. 方法
在一个类中,可能出现三种方法,实例方法、静态方法和类方法。
1)实例方法
实例方法的第一个参数必须是”self”,”self”类似于C++中的”this”。
实例方法只能通过类实例进行调用,这时候”self”就代表这个类实例本身。通过”self”可以直接访问实例的属性。
class Student(object):
'''
this is a Student class
'''
count = 0
books = []
def __init__(self, name, age):
self.name = name
self.age = age def printInstanceInfo(self):
print "%s is %d years old" %(self.name, self.age)
pass wilber = Student("Wilber", 28)
wilber.printInstanceInfo()
2)类方法
类方法以cls作为第一个参数,cls表示类本身,定义时使用@classmethod装饰器。通过cls可以访问类的相关属性。
class Student(object):
'''
this is a Student class
'''
count = 0
books = []
def __init__(self, name, age):
self.name = name
self.age = age @classmethod
def printClassInfo(cls):
print cls.__name__
print dir(cls)
pass Student.printClassInfo()
wilber = Student("Wilber", 28)
wilber.printClassInfo()
3)静态方法
与实例方法和类方法不同,静态方法没有参数限制,既不需要实例参数,也不需要类参数,定义的时候使用@staticmethod装饰器。
同类方法一样,静态法可以通过类名访问,也可以通过实例访问。
class Student(object):
'''
this is a Student class
'''
count = 0
books = []
def __init__(self, name, age):
self.name = name
self.age = age @staticmethod
def printClassAttr():
print Student.count
print Student.books
pass Student.printClassAttr()
wilber = Student("Wilber", 28)
wilber.printClassAttr()
这三种方法的主要区别在于参数,实例方法被绑定到一个实例,只能通过实例进行调用;但是对于静态方法和类方法,可以通过类名和实例两种方式进行调用。
3. 访问控制
在Python中,通过单下划线”_”来实现模块级别的私有化,一般约定以单下划线”_”开头的变量、函数为模块私有的,也就是说”from moduleName import *”将不会引入以单下划线”_”开头的变量、函数。
现在有一个模块lib.py,内容用如下,模块中一个变量名和一个函数名分别以”_”开头:
numA = 10
_numA = 100 def printNum():
print "numA is:", numA
print "_numA is:", _numA def _printNum():
print "numA is:", numA
print "_numA is:", _numA
当通过下面代码引入lib.py这个模块后,所有的以”_”开头的变量和函数都没有被引入,如果访问将会抛出异常:
from lib import *
print numA
printNum() print _numA
#print _printNum()
双下划线”__”
对于Python中的类属性,可以通过双下划线”__”来实现一定程度的私有化,因为双下划线开头的属性在运行时会被”混淆”(mangling)。
在Student类中,加入了一个”__address”属性:
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
self.__address = "Shanghai"
pass wilber = Student("Wilber", 28)
print wilber.__address
当通过实例wilber访问这个属性的时候,就会得到一个异常,提示属性”__address”不存在。
其实,通过内建函数dir()就可以看到其中的一些原由,”__address”属性在运行时,属性名被改为了”_Student__address”(属性名前增加了单下划线和类名)
>>> wilber = Student("Wilber", 28)
>>> dir(wilber)
['_Student__address', '__class__', '__delattr__', '__dict__', '__doc__', '__form
at__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__r
educe__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '
__subclasshook__', '__weakref__', 'age', 'name']
所以说,即使是双下划线,也没有实现属性的私有化,因为通过下面的方式还是可以直接访问”__address”属性:
>>> wilber = Student("Wilber", 28)
>>> print wilber._Student__address
Shanghai
双下划线的另一个重要的目地是,避免子类对父类同名属性的冲突。
class A(object):
def __init__(self):
self.__private()
self.public() def __private(self):
print 'A.__private()' def public(self):
print 'A.public()' class B(A):
def __private(self):
print 'B.__private()' def public(self):
print 'B.public()' b = B()
当实例化B的时候,由于没有定义__init__函数,将调用父类的__init__,但是由于双下划线的”混淆”效果,”self.__private()”将变成 “self._A__private()”
“_”和” __”的使用 更多的是一种规范/约定,不没有真正达到限制的目的:
“_”:以单下划线开头的表示的是protected类型的变量,即只能允许其本身与子类进行访问;同时表示弱内部变量标示,如,当使用”from moduleNmae import *”时,不会将以一个下划线开头的对象引入。
“__”:双下划线的表示的是私有类型的变量。只能是允许这个类本身进行访问了,连子类也不可以,这类属性在运行时属性名会加上单下划线和类名。
总结
本文介绍了Python中class的一些基本点:
- 实例数据属性和类数据属性的区别,以及属性隐藏
- 实例方法,类方法和静态方法直接的区别
- Python中通过”_”和”__”实现的访问控制
Python学习总结19:类(一)的更多相关文章
- Python学习 Part7:类
Python学习 Part7:类 1. 作用域和命名空间 命名空间(namespace)就是一个从名称到对象的映射. 命名空间的一些实例:内置名称集(函数,像abs(),和内置异常名称),一个模块中的 ...
- python学习笔记4_类和更抽象
python学习笔记4_类和更抽象 一.对象 class 对象主要有三个特性,继承.封装.多态.python的核心. 1.多态.封装.继承 多态,就算不知道变量所引用的类型,还是可以操作对象,根据类型 ...
- Python学习总结19:类(二)
参考:http://python.jobbole.com/82308/ 继承和__slots__属性 1. 继承 在Python中,同时支持单继承与多继承,一般语法如下: class SubCl ...
- 【Python学习之七】类和对象
环境 虚拟机:VMware 10 Linux版本:CentOS-6.5-x86_64 客户端:Xshell4 FTP:Xftp4 python3.6 一.面向对象编程1.概念(1)面向对象编程(OOP ...
- Python学习笔记 - day7 - 类
类 面向对象最重要的概念就是类(Class)和实例(Instance),比如球类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同.在Python中,定义类 ...
- python学习(十)元类
python 可以通过`type`函数创建类,也可通过type判断数据类型 import socket from io import StringIO import sys class TypeCla ...
- python学习笔记1-元类__metaclass__
type 其实就是元类,type 是python 背后创建所有对象的元类 python 中的类的创建规则: 假设创建Foo 这个类 class Foo(Bar): def __init__(): ...
- Python学习(19)正则表达式
目录 Python 正则表达式 re.match 函数 re.search 方法 re.match 函数与 re.search 方法区别 检索和替换 正则表达式修饰符 - 可选标志 正则表达式模式 正 ...
- Python学习笔记12—类
典型的类和调用方法: #!/usr/bin/env Python # coding=utf-8 __metaclass__ = type #新式类 class Person: #创建类 def __i ...
随机推荐
- 设置myeclipse 项目编码(UTF-8)
设置myeclipse开发项目默认编码为UTF-8Window-->Preferences-->General-->Workspace-->(Text file encodin ...
- 页面瀑布流布局的实现 javascript+css
先看所谓的瀑布流布局 在不使用瀑布流布局的情况下,当页面要显示不同高度的图片时,会如下面显示 下面的元素总是和最靠近它的元素对齐. 为了使元素能够在我们想要的位置上显示,我们使用绝对定位. 说一下大体 ...
- ucenter小结
经历了一天的折腾,大概搞清楚的ucenter接入应用的方法.总结如下: 一.下载安装ucenter.这个很简单. 二.然后就是接入应用. 1.先在你项目的根目录copy一份uc_client文件夹. ...
- php数据访问:pdo用法、事物回滚功能和放sql注入功能
PDO: 一.含义: 数据访问抽象层 二.作用 通过PDO能够访问其它的数据库 三. 用法: 1.造对象 ① $pdo ...
- FW:使用weave管理docker网络
Posted on 2014-11-12 22:20 feisky 阅读(1761) 评论(0) 编辑 收藏 weave简介 Weave creates a virtual network that ...
- yii2 实现多表联查
- 使用Dom的Range对象处理chrome和IE文本光标位置
有这样一段js: var sel = obj.createTextRange(); sel.move('character', num); sel.collapse(); sel.select(); ...
- Cocos2d-JS切换场景与切换特效
var HelloWorldLayer = cc.Layer.extend({ sprite:null, ctor:function () { //////////////////////////// ...
- 算法训练 Hanoi问题
算法训练 Hanoi问题 时间限制:1.0s 内存限制:512.0MB 问题描述 如果将课本上的Hanoi塔问题稍做修改:仍然是给定N只盘子,3根柱子,但是允许每次最多移动相邻的 ...
- GitLab使用方法
注意只有master权限的用户才可以push到主线master分支上(默认受保护)(当一个新版本的app定版之后,才会提交到master分支上,平时不建议使用该分支),developer没有push到 ...