python 面向对象

时间:2019-03-20
本文章向大家介绍python 面向对象,主要包括python 面向对象使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

数据类型

运算符

# 算数运算符+,-,×,/,%,//,**,分别是加,减,乘,除,求模,向下取整,幂
print(2**3, 23//4)              # result 8,5
# 比较运算符<,>,=>,=<=,!=,==
# 赋值运算符+=,=,-=,/=,**=,%=,//=
# 位运算&,|,^,~,<<,>>,两个为1时1,两个其中一个1时为1,两个不相同时为1,取反,左移,右移
print(13 << 2, 8 ^ 4)                  # 13=1101,13<<2==110100==52      8=1000 4=0100 8^4=1100=12
# 逻辑运算符 and or not
# 成员运算符 in not in
# 身份运算符 is is not

数字
支持三种,int(),float(),complex()

# 进制的转换 int(value,base),value是str
# bin() oct() hex() dec()直接从数字转换
test_number_dec = 10
test_number_str = str(test_number_dec)
test_number_bin = int(test_number_str, 2)
test_number_oct = int(test_number_str, 8)
test_number_hex = int(test_number_str, 16)
print("{十进制}    {二进制}   {八进制}   {十六进制}".format(十进制=test_number_dec, 二进制=test_number_bin,
                                               八进制=test_number_oct,十六进制=test_number_hex))
print("{}   {}  {}  {}".format(test_number_dec, bin(test_number_dec), oct(test_number_dec), hex(test_number_dec)))
# result:
# 10   2       8     16
# 10   0b1010  0o12  0xa

import  math
# 数学函数
'''
abs()               绝对值
ceil()              向上取整
exp(x)              e的x次幂
floor(x)            向下取整
log(x)              math.log(100,10)返回2.0
max(x1, x2,...)     最大值
min(x1, x2,...)     最小值
pow(x, y)           x的y次方
round(x [,n])       四舍五入
acos(x)	            返回x的反余弦弧度值。
asin(x)            	返回x的反正弦弧度值。
atan(x)         	返回x的反正切弧度值。
atan2(y, x)	        返回给定的 X 及 Y 坐标值的反正切值。
cos(x)	            返回x的弧度的余弦值。
hypot(x, y)	        返回欧几里德范数 sqrt(x*x + y*y)。
sin(x)	            返回的x弧度的正弦值。
tan(x)	            返回x弧度的正切值。
degrees(x)	        将弧度转换为角度,如degrees(math.pi/2) , 返回90.0
radians(x)	        将角度转换为弧度
'''

字符串

import  math
# str运算符
'''
+	        字符串连接	
*	        重复输出字符串	a*2 
[]	        通过索引获取字符串中字符	
[ : ]	    截取字符串中的一部分,遵循左闭右开原则,str[0,2] 是不包含第 3 个字符的。
in	        成员运算符 
not in	    成员运算符 
r/R	        原始字符串 
'''
print('zylg'*2)         # result:zylgzylg

# str格式化
'''
  %c	 格式化字符及其ASCII码
  %s	 格式化字符串
  %d	 格式化整数
  %u	 格式化无符号整型
  %o	 格式化无符号八进制数
  %x	 格式化无符号十六进制数
  %X	 格式化无符号十六进制数(大写)
  %f	 格式化浮点数字,可指定小数点后的精度
  %e	 用科学计数法格式化浮点数
格式化操作符辅助指令:
*	    定义宽度或者小数点精度
-	    用做左对齐
+	    在正数前面显示加号( + )
<sp>	在正数前面显示空格
#	    在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X')
0	    显示的数字前面填充'0'而不是默认的空格
%	    '%%'输出一个单一的'%'
(var)	映射变量(字典参数)
m.n.	m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)
'''
for i in range(0, 101, 20):
    print('%-+10.2f' % i)

'''
result:(左对齐,正数前面加上+,两位小数)
+0.00     
+20.00    
+40.00    
+60.00    
+80.00    
+100.00 
'''
# 字符串內建函数
'''
capitalize()                               将字符串的第一个字符转换为大写
count(str, beg= 0,end=len(string))         返回 str 在 string 里面出现的次数
bytes.decode(encoding="utf-8", errors="strict")
encode(encoding='UTF-8',errors='strict')
expandtabs(tabsize=8)                    把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。
endswith(suffix, beg=0, end=len(string))
startswith(suffix)
lower()
upper()
split(str="", num=string.count(str))
replace(old, new [, max])                   把 将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次。
len(string)
isdigit()
islower()
isupper()
isnumeric()
isspace()
lstrip()                                    截掉左边空
rstrip()                                    截掉左边空
strip([chars])
zfill (width)                               返回长度为 width 的字符串,原字符串右对齐,前面填充0
'''


def get_user(userfile):
    # 定义一个用户列表
    user_list = []
    with open(userfile) as f:
        for line in f:
            if not line.startswith('#') and line:
                if len(line.split()) == 4:
                    user_list.append(line.split())
                else:
                    print("user.conf配置错误")
    return user_list



list

my_list_1 = ['zylg', 'zxw', 1997, 2000]
# list 脚本操作符
'''
*重复         my_list_1*4
+添加         my_list_2+my_list_1
len(my_list) 长度
'''
print(my_list_1*4)
print(my_list_1+my_list_1)
print(len(my_list_1))
print(my_list_1[-4:])
# list 操作方法
'''
list.append(obj)                在列表末尾添加新的对象
list.extend(seq)                在列表末尾一次性追加另一个序列中的多个值
list.index(obj)                 从列表中找出某个值第一个匹配项的索引位置
list.insert(index, obj)         将对象插入列表
list.pop([index=-1])            移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj)                移除列表中某个值的第一个匹配项
list.clear()
list.copy()
list.sort( key=None, reverse=False) 
list.reverse()
'''

字典

# 字典
my_dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
'''
clear()
copy()
get(key, default=None)
items()                 以列表返回可遍历的(键, 值) 元组数组
keys()
values()
pop(key[,default])
'''

set

# 集合(set)是一个无序的不重复元素序列。
my_set = set(("Google", "Runoob", "Taobao", "Facebook"))
'''
x.union(y)               	返回两个集合的并集
x.intersection(y)           返回两个集合的交集
x.symmetric_difference(y)   返回两个集合的交集之外的集合
add()	                    为集合添加元素
clear()	                    移除集合中的所有元素
copy()	                    拷贝一个集合
set.discard(value)          删除指定元素
issubset()	                判断指定集合是否为该方法参数集合的子集。
'''
print(my_set)

条件控制和结构循环

if 表达式1:
    语句
    if 表达式2:
        语句
    elif 表达式3:
        语句
    else:
        语句
elif 表达式4:
    语句
else:
    语句
count = 0
while count < 5:
   print (count, " 小于 5")
   count = count + 1
else:
   print (count, " 大于或等于 5")




for <variable> in <sequence>:
	[pass]
    <statements>
else:
    <statements>
  

面向对象

双下划线开头为私有,不能直接使用

#!/usr/bin/python3
 
#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
 
#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
 
#另一个类,多重继承之前的准备
class speaker():
    topic = ''
    name = ''
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    def speak(self):
        print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))
 
#多重继承
class sample(speaker,student):
    a =''
    def __init__(self,n,a,w,g,t):
        student.__init__(self,n,a,w,g)
        speaker.__init__(self,n,t)
 
test = sample("Tim",25,80,4,"Python")
test.speak()   #方法名同,默认调用的是在括号中排前地父类的方法