- ·上一篇文章:Python 内置函数
- ·下一篇文章:Python 正则表达式
Python 面向对象
+ other.a, self.b + other.b)v1 = Vector(2,10)v2 = Vector(5,-2)print v1 + v2以上代码执行结果如下所示:
Vector(7,8)类属性与方法类的私有属性__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。类的方法在类的内部,使用 def 关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数类的私有方法__private_method:两个下划线开头,声明该方法为私有方法,不能在类的外部调用。在类的内部调用 self.__private_methods实例
#!/usr/bin/python
# -*- coding:
UTF-8 -*-
class JustCounter:
__secretCount = 0
# 私有变量publicCount = 0
# 公开变量def count(self):
self.__secretCount += 1self.publicCount += 1print self.__secretCountcounter = JustCounter()counter.count()counter.count()print counter.publicCountprint counter.__secretCount
# 报错,实例不能访问私有变量Python 通过改变名称来包含类名:
122Traceback (most recent call last):
File "test.py", line 17, in <module> print counter.__secretCount
# 报错,实例不能访问私有变量AttributeError:
JustCounter instance has no attribute '__secretCount'Python不允许实例化的类访问私有数据,但你可以使用 object._className__attrName( 对象名._类名__私有属性名 )访问属性,参考以下实例:
#!/usr/bin/python
# -*- coding:
UTF-8 -*-
class Runoob:
__site = "www.k88.net"k88 = Runoob()print k88._Runoob__site执行以上代码,执行结果如下:www.k88.net单下划线、双下划线、头尾双下划线说明:__foo__:
定义的是特殊方法,一般是系统定义名字 ,类似 __init__() 之类的。_foo:
以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *__foo:
双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。
Vector(7,8)类属性与方法类的私有属性__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。类的方法在类的内部,使用 def 关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数类的私有方法__private_method:两个下划线开头,声明该方法为私有方法,不能在类的外部调用。在类的内部调用 self.__private_methods实例
#!/usr/bin/python
# -*- coding:
UTF-8 -*-
class JustCounter:
__secretCount = 0
# 私有变量publicCount = 0
# 公开变量def count(self):
self.__secretCount += 1self.publicCount += 1print self.__secretCountcounter = JustCounter()counter.count()counter.count()print counter.publicCountprint counter.__secretCount
# 报错,实例不能访问私有变量Python 通过改变名称来包含类名:
122Traceback (most recent call last):
File "test.py", line 17, in <module> print counter.__secretCount
# 报错,实例不能访问私有变量AttributeError:
JustCounter instance has no attribute '__secretCount'Python不允许实例化的类访问私有数据,但你可以使用 object._className__attrName( 对象名._类名__私有属性名 )访问属性,参考以下实例:
#!/usr/bin/python
# -*- coding:
UTF-8 -*-
class Runoob:
__site = "www.k88.net"k88 = Runoob()print k88._Runoob__site执行以上代码,执行结果如下:www.k88.net单下划线、双下划线、头尾双下划线说明:__foo__:
定义的是特殊方法,一般是系统定义名字 ,类似 __init__() 之类的。_foo:
以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *__foo:
双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。
Python 面向对象