一、构造函数
def __init__()
构造函数
i = 123 # Class Field
def __init__(self):
self.i = 12345 # Instance Field
def getClassName(self):
print 'Hello,I am A'
pass
myname = 'peter'
def sayhello(hello):
print "say hello to %s" % hello.myname
MyTest().sayhello()
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
print value
yes no
yes no yaaaass
Python Class 同样包含类型和实例两种成员。
>>> class Class1:
>>> print Class1.i
123
>>> print Class1().i
12345
self
相当于this
我们可以在成员名称前添加 "__" 使其成为私有成员。
二 继承(inherite),B继承A
>>> class A:
>>> class B(A):
>>> a=A()
>>> b=B()
>>> a.getClassName()
Hello,I am A
>>> b.getClassName()
Hello,I am A
>>>
三、执行
class MyTest:
if __name__ == "__main__":
四 isinstance说明如下:
isinstance(object, class-or-type-or-tuple) -> bool
其第一个参数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。若对象的类型与参数二的类型相同则返回True。若参数二为一个元组,则若对象类型与元组中类型名之一相同即返回True。
>>>isinstance(lst, list)
Trueisinstance(lst, (int, str, list))
True
>>>isinstance(lst, (int, str, list))
True
五 list extend (扩展) 与 append (追加) 的差别
>>>li=['a','b']
>>>li.extend(['c','d'])
>>>li
['a', 'b', 'c', 'd']
>>>li.append(['e','f'])
>>>li
['a', 'b', 'c', 'd',['e','f']]
六 Python 字符串操作(截取/替换/查找/分割)
Python 截取字符串使用 变量[头下标:尾下标],就可以截取相应的字符串,其中下标是从0开始算起,可以是正数或负数,下标可以为空表示取到头或尾。
Python代码
# 例1:字符串截取
str = '12345678'
print str[0:1]
>> 1
# 输出str位置0开始到位置1以前的字符
print str[1:6]
>> 23456
# 输出str位置1开始到位置6以前的字符
num = 18
str = '0000' + str(num) # 合并字符串
print str[-5:]
# 输出字符串右5位
>> 00018
Python 替换字符串使用 变量.replace("被替换的内容","替换后的内容"[,次数]),替换次数可以为空,即表示替换所有。要注意的是使用replace替换字符串后仅为临时变量,需重新赋值才能保存。
Python代码
# 例2:字符串替换
str = 'akakak'
str = str.replace('k',' 8') # 将字符串里的k全部替换为8
print str
>> 'a8a8a8'
# 输出结果
Python 查找字符串使用 变量.find("要查找的内容"[,开始位置,结束位置]),开始位置和结束位置,表示要查找的范围,为空则表示查找所有。查找到后会返回位置,位置从0开始算,如果每找到则返回-1。
Python代码
# 例3:字符串查找
str = 'a,hello'
print str.find('hello') # 在字符串str里查找字符串hello
>> 2
# 输出结果
Python 分割字符串使用 变量.split("分割标示符号"[分割次数]),分割次数表示分割最大次数,为空则分割所有。
Python代码
例4:字符分割
str = 'a,b,c,d'
strlist = str.split(',')
# 用逗号分割str字符串,并保存到列表
for value in strlist:
# 循环输出列表值
>> a
# 输出结果
>> b
>> c
>> d
七 strip lstrip rstrip
Python中的strip用于去除字符串的首位字符,同理,lstrip用于去除左边的字符,rstrip用于去除右边的字符。这三个函数都可传入一个参数,指定要去除的首尾字符。注意的是,传入的是一个字符数组,编译器去除两端所有相应的字符,直到没有匹配的字符,比如:
theString = 'saaaay yes no yaaaass'
print theString.strip('say')
theString依次被去除首尾在['s','a','y']数组内的字符,直到字符在不数组内。所以,输出的结果为:
yes no
比较简单吧,lstrip和rstrip原理是一样的。注意:当没有传入参数时,是默认去除首尾空格的。
theString = 'saaaay yes no yaaaass'
print theString.strip('say')
print theString.strip('say ') #say后面有空格
print theString.lstrip('say')
print theString.rstrip('say')
运行结果:
es no
saaaay yes no