kayson@kayson-virtual-machine:~$ cat fangfa.py
# ! /usr/bin/python
# -*- coding:utf-8 -*-
'''python方法
在python中方法分为:公有方法、私有方法、类方法和静态方法'''
class people():
name = ''
__age = 0
def __init__(self):
self.name = '张三'
self.__age = 23
def showinfo():
return self.__age
def fun1(self):
print "fun1:\n"
print "it's public method"
def __fun2(self):
print "私有不可以类的外部进行调用"
print "fun2:\n"
print "it's privite method"
if __name__ == '__main__':
p1 = people()
print p1.name
print p1.showinfo() #打印showinfo函数来打印私有属性
print p1.__dict__ #打印公有方法
p1.fun1()
p1.__fun2() #打印__fun2私有方法
kayson@kayson-virtual-machine:~$ python fangfa.py
张三
>
{'_people__age': 23, 'name': '\xe5\xbc\xa0\xe4\xb8\x89'}
fun1:
it's public method
# --------打印__fun2私有方法报错。----
Traceback (most recent call last):
File "fangfa.py", line 28, in
p1.__fun2()
AttributeError: people instance has no attribute '__fun2'
''' 要想将私有方法打印出来,解决办法跟打印私有属性一样,
需要定义个中间方法函数来做跳转'''
# ---用代码完整解释 ----
kayson@kayson-virtual-machine:~$ cat fangfa.py
# ! /usr/bin/python
# -*- coding:utf-8 -*-
class people():
name = ''
__age = 0
def __init__(self):
self.name = '张三'
self.__age = 23
def showinfo():
return self.__age
def fun1(self):
print "fun1:\n"
print "it's public method"
def __fun2(self):
print "私有不可以类的外部进行调用"
print "fun2:\n"
print "it's privite method"
def show(self): # 定义show()为中转方法(方法)
self.__fun2() # 调用私有方法__fun2()
if __name__ == '__main__':
p1 = people()
print p1.name
print p1.showinfo
print p1.__dict__
p1.fun1() # 调用fun1()公有方法
p1.show() # 调用中转方法show()
kayson@kayson-virtual-machine:~$ python fangfa.py
张三
>
{'_people__age': 23, 'name': '\xe5\xbc\xa0\xe4\xb8\x89'}
fun1:
it's public method
# ---打印私有方法成功
私有不可以类的外部进行调用
fun2:
it's privite method
# ----类方法----
kayson@kayson-virtual-machine:~$ cat leifangfa.py
# ! /usr/bin/python
# -*- coding:utf-8 -*-
class people():
name = ''
__age = 0
@classmethod # class 修饰器,使得fun3变为类方法
'''若将其注释,则会报错
kayson@kayson-virtual-machine:~$ python leifangfa.py
Traceback (most recent call last):
File "leifangfa.py", line 28, in
people.fun3()
TypeError: unbound method fun3() must be called with people instance as first argument (got nothing instead)
'''
def fun3(self):
print "我是类方法fun3"
if __name__ == '__main__':
people.fun3()
kayson@kayson-virtual-machine:~$ python leifangfa.py
我是类方法fun3
# ----- 静态方法 ----
kayson@kayson-virtual-machine:~$ cat fangfa.py
#! /usr/bin/python
#-*- coding:utf-8 _*_
class people():
name=''
__age=0
@staticmethod # class修饰器,使得fun4为静态方法
def fun4(): #定义静态方法时,不需要self形参
print "我是静态方法fun4"
if __name__=='__main__':
people.fun4()
kayson@kayson-virtual-machine:~$ python jingtai.py
我是静态方法fun4
阅读(1578) | 评论(0) | 转发(0) |