类是所有面向对象语言的特色,Python也不例外,下面是一个很简单的例子,其中的self有点像Java里面的this关键字:
class Worker:
def __init__(self, name, pay):
self.name = name
self.pay = pay
def lastName(self):
return self.name.split()[-1]
def giveRaise(self, percent):
self.pay *= (1.0 + percent)
bob = Worker('Zhang luoyang', 15000)
sue = Worker('Sue Jones', 60000)
print bob.lastName()
数字操作:
a = 3
b = 4
print a+1,a-1
print b*3, b/2
print a%2, b**2
print 2 + 4.0, 2.0 ** b
print b / 2 +a
print b / (2.0+a)
print 1 /2.0
print 1 /3.0
import math
print math.floor(2.5)
print math.floor(-2.5)
print math.trunc(-2.5)
print math.trunc(2.5)
print(2, 4), 2 ** 4
print abs(-42.0), sum((1,2,3,4))
print min(3,1,2,4),max(3,1,2,4)
print math.floor(2.567), math.floor(-2.567)
print math.trunc(2.567), math.trunc(-2.567)
print int(2.567), int(-2.567)
print round(2.567),round(2.467),round(2.567,2)
import random
print random.random()
print random.randint(1,10)
print random.randint(1,10)
print random.choice(['zhangluoyang','is a good man'])
比较操作:
print 1<2
print 2.0>1
print 1<2<3
print 1<2 and 2<3
print 5<7>6
print 5<7 and 7>6
print 1 ==2 < 3
print 1 ==2 and 2 < 3
print 10 / 4
print 10 / 4.0
print 10 // 4.0
位操作:
x = 1
print x << 2
print x | 2
print x & 1
集合
x = set('abcde')
y = set('bdxyz')
print x
print y
print 'e' in x
print x - y
print x | y
print x & y
print x ^ y
z = x.intersection(y)
print z.add('SPAM')
print z
print x.update(set(['X','Y']))
print x
z.remove('b')
print z
for item in set('abc'): print(item * 3)
S = set([1,2,3])
print S | set([3,4])
print S.union([3,4])
print S.intersection((1,3,5))
print S.issubset(range(-5,5))
S1 = {1,2,3,4}
print S1 & {1,3}
print {1,5,3,6} | S1
print S1 - {1,3,4}
print S1 > {1,3,8}
S1.add(77)
print S1
print {x ** 2 for x in [1,2,3,4]}
print {x for x in 'spam'}
print {c * 4 for c in 'spam'}
S = {c * 4 for c in 'spam'}
print S | {'mmmm', 'xxxx'}
print S & {'mmmm','xxxx'}
L = [1,2,1,3,2,5,4]
print set(L)
L = list(set(L))
print L