python 面向?qū)ο?/code>
class Foo():
def __init__(self,name,age):
self.name = name
self.age = age
def skill(self):
print(self.name ,self.age,"開大快跑")
obj=Foo("安妮",16)
obj.skill()
result:
安妮 16 開大快跑
self代表類的實(shí)例,而非類
類的方法與普通的函數(shù)只有一個(gè)特別的區(qū)別——它們必須有一個(gè)額外的第一個(gè)參數(shù)名稱, 按照慣例它的名稱是 self。
class Test:
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()
以上實(shí)例執(zhí)行結(jié)果為:
<__main__.Test instance at 0x10d066878>
__main__.Test
從執(zhí)行結(jié)果可以很明顯的看出娇斩,self 代表的是類的實(shí)例,代表當(dāng)前對(duì)象的地址穴翩,而 self.class 則指向類犬第。
self 不是 python 關(guān)鍵字,我們把他換成 runoob 也是可以正常執(zhí)行的:
Python內(nèi)置類屬性
__dict__ : 類的屬性(包含一個(gè)字典芒帕,由類的數(shù)據(jù)屬性組成)
__doc__ :類的文檔字符串
__name__: 類名
__module__: 類定義所在的模塊(類的全名是'__main__.className'歉嗓,如果類位于一個(gè)導(dǎo)入模塊mymod中,那么className.__module__ 等于 mymod)
__bases__ : 類的所有父類構(gòu)成元素(包含了一個(gè)由所有父類組成的元組)
Python內(nèi)置類屬性調(diào)用實(shí)例如下:
實(shí)例
class Person():
city = "BeiJing" # 類的數(shù)據(jù)屬性
def __init__(self,name,age):
self.Name = name
self.Age = age
def run(self):
print('{} is running'.format(self.Name))
anni=Person("anni",16)
anni.run()
print ("Person.__doc__:", Person.__doc__)
print ("Person.__name__:", Person.__name__)
print ("Person.__module__:", Person.__module__)
print ("Person.__bases__:", Person.__bases__)
print ("Person.__dict__:", Person.__dict__)
result:
Person.__doc__: None
Person.__name__: Person
Person.__module__: __main__
Person.__bases__: (<class 'object'>,)
Person.__dict__: {'__module__': '__main__', 'city': 'BeiJing', '__init__': <function Person.__init__ at 0x00000000025EA8C8>, 'run': <function Person.run at 0x00000000025EA7B8>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
類方法
class Person():
city = "BeiJing" # 類的數(shù)據(jù)屬性
def __init__(self,name,age):
self.Name = name
self.Age = age
def run(self):
print('{} is running'.format(self.Name))
@classmethod //類方法
def sleep(cls): //cls替代self
print(cls)
anni=Person("anni",16)
anni.run()
Person.sleep()
anni.sleep()
result:
anni is running
<class '__main__.Person'>
<class '__main__.Person'>
list背蟆、dict 等都成為工廠函數(shù)鉴分,它們本身就是一個(gè)類,誰調(diào)誰好使 誰調(diào)带膀,就向誰的列表中添加
li = list('yangge')
print(type(li))
l2 = list('yangge')
l2.append(1)
li.append(2)
print(l2)
print(li)
result:
<class 'list'>
['y', 'a', 'n', 'g', 'g', 'e', 1]
['y', 'a', 'n', 'g', 'g', 'e', 2]
靜態(tài)方法
class Math():
@staticmethod
def Add(a,b):
print(a+b)
Math.Add(1,3) #調(diào)用函數(shù)應(yīng)該有2個(gè)參數(shù)就傳2個(gè)參數(shù)
op=Math()
# 實(shí)例也可以使,但通常靜態(tài)方法都是給類用的,實(shí)例在使時(shí)喪失了自動(dòng)動(dòng)傳參的機(jī)制
op.Add(1,4)
result:
4
5
# 需求
# 1.定義三個(gè)類:Student Teacher ClassName
# 2.可以通過 Teacher的實(shí)例志珍,可以查詢到這個(gè)對(duì)象的所有學(xué)生,還可以查詢到這個(gè)對(duì)象所管理的班級(jí)
# 3.學(xué)生必須創(chuàng)建4個(gè)垛叨,且至少分配給兩個(gè)老師伦糯,還被分別分配到了兩個(gè)班級(jí)
# a c1 laowang
# b c1 laowang
# c c2 laoguo
# d c2 laoguo
class Class():
all_class=[]
def __init__(self,name,teacher):
self.name=name
self.teacher=teacher
Class.all_class.append(self)
class Student():
all_stu=[]
def __init__(self,name,teacher,class_name):
self.teacher=teacher
self.name=name
self.class_name=class_name
Student.all_stu.append(self)
class Teacher():
def __init__(self,teacher):
self.stu_list=[]
self.class_list=[]
self.teacher=teacher
def echo_stu(self):
for n in Student.all_stu:
if(self.teacher == n.teacher):
self.stu_list.append(n.name)
print(self.stu_list)
def echo_class(self):
for n in Class.all_class:
if(self.teacher == n.teacher):
self.class_list.append(n.name)
print(self.class_list)
a = Student('a','laowang','c1')
b = Student('b','laowang','c1')
c = Student('c','laoguo','c2')
d = Student('d','laoguo','c2')
c1= Class("c1","laowang")
c2= Class("c2","laoguo")
laowang = Teacher("laowang")
laowang.echo_stu()
laowang.echo_class()
laoguo = Teacher("laoguo")
laoguo.echo_stu()
laoguo.echo_class()
__mro__ c3算法
http://python.jobbole.com/85685/
繼承 覆蓋
class Vehicle:
def __init__(self,name,brand,date):
self.name=name
self.brand=brand
self.date=date
def run(self):
print( "the {} is running".format(self.name))
#對(duì)父類車進(jìn)行繼承
class car(Vehicle):
def __init__(self,name,brand,date,speed):
# self.name=name #法一 在子類中添加新的參數(shù) 調(diào)用父類初始化化的三種方法
# self.brand=brand
# self.date=date
#Vehicle.__init__(self,name,brand,date) #法二
super().__init__(name,brand,date) #法三 python3的方法 且沒有self
self.speed=speed
def run(self): #覆蓋父類的方法
print("this {} is running speed {}".format(self.name,self.speed))
x6=car("寶馬","x6","070101","200km/h")
x6.run()
print(x6.speed)
#多態(tài)
class Vehicle:
def __init__(self,name,brand,date):
self.name=name
self.brand=brand
self.date=date
def run(self):
print( "the {} is running".format(self.name))
#對(duì)父類車進(jìn)行繼承
class car(Vehicle):
def __init__(self,name,brand,date,speed):
super().__init__(name,brand,date) #法三 python3的方法 且沒有self
self.speed=speed
def run(self): #覆蓋父類的方法
print("this {} is running speed {}".format(self.name,self.speed))
class bike(Vehicle):
def __init__(self,name,brand,date,speed):
super().__init__(name,brand,date) #法三 python3的方法 且沒有self
self.speed=speed
def run(self): #覆蓋父類的方法
print("this {} is running speed {}".format(self.name,self.speed))
my_car=car("寶馬","x6","070101","200km/h")
my_bike=bike("保時(shí)捷","x1","070101","20km/h")
def func(obj): # 為了很好的展示多態(tài)性,還有再借個(gè)函數(shù)
obj.run()
func(my_car)
func(my_bike)
# @property, 指 getter 方法
# @name.setter敛纲, 指 setter 方法
class A():
def __init__(self,name,age):
self.__name=name #添加___ 私有屬性
self.age=age
@property
def name(self):
print("getter 被調(diào)用")
return self.__name
@name.setter
def name(self,__name):
print("settter 被設(shè)置了")
self.__name=__name
a = A('shark',19)
a.age =10 #可以改寫age
#a.name="zhu" #不能改寫 會(huì)報(bào)錯(cuò)
a.name="zhu"
print(a.name)
#print(a.name)
result:
settter 被設(shè)置了
getter 被調(diào)用
zhu
#反射(自饰够鳌)
#模塊是以.py結(jié)尾
class A():
def __init__(self,name,age):
self.name=name
self.age=age
obj=A('xiaoguo',17)
if hasattr(obj,'age'):
getname=getattr(obj,'name')
print(getname)
setage=setattr(obj,'age',18)
getage=getattr(obj,'age')
print(getage)
print(A.__dict__) #只有實(shí)例才有name屬性
print(obj.__dict__) #只有實(shí)例才有name屬性
#result:
# xiaoguo
# 18
# {'__module__': '__main__', '__init__': <function A.__init__ at 0x00000000021FA840>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
# {'name': 'xiaoguo', 'age': 18}
import cls #導(dǎo)入上一個(gè)例子模塊
a= getattr(cls,'A') #通過反射得到A這個(gè)類
print(a)
obj1 = a("yang",29)
print(getattr(obj1,'name'))
print(isinstance(obj1,a))
# print(globals())
導(dǎo)入包里面的模塊
# from pak import host,main #法一 pak是個(gè)文件夾里面有host.py,main.py
import sys # 模塊搜索路徑存儲(chǔ)在 system 模塊的 sys.path 變量中
import pak.host #法二
import pak.main #法二
print(sys.path)
print(pak.host.host)
pak.main.connection("zz",80,"gg","root")
導(dǎo)入模塊
from conf import settings #可以將settins.py放到conf目錄里
host_info={}
from importlib import import_module #重點(diǎn) 以前沒寫出來卡住了
for key,value in settings.module_dic.items():
# print(key,' ',value)
a,b = value.rsplit('.', 1)
module_obj = import_module(a) #***
# print(module_obj)
info=(getattr(module_obj,b)())
host_info[key]=info
print(host_info)
魔術(shù)方法
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return "{}---{}".format(self.name,self.age) #要有返回值
obj1=Person("xiaoguo",19)
print(obj1)
抽象類 用于其他類繼承他 被人繼承他就得去實(shí)現(xiàn)他的方法
from abc import ABCMeta,abstractmethod
class chouxiang(metaclass=ABCMeta):
@abstractmethod
def get_info(self):
pass
class a(chouxiang):
def get_info(self):
return "hello"
import abc
class chouxiang(metaclass=abc.ABCMeta):
@abc.abstractclassmethod
def foo(self):
pass
paramiko 環(huán)境要裝paramiko
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
key_obj = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
ssh.connect('119.29.175.88',22,'root',pkey=key_obj)
stdin,stdout,stderr = ssh.exec_command('ip a')
res=str(stdout.read(),encoding='utf-8')
paramiko ssh
法1
#實(shí)例化SSHClient
client = paramiko.SSHClient()
#自動(dòng)添加策略,保存服務(wù)器的主機(jī)名和密鑰信息
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#連接SSH服務(wù)端载慈,以用戶名和密碼進(jìn)行認(rèn)證
client.connect(ip,username=user,password=passwd)
#打開一個(gè)Channel并執(zhí)行命令
stdin,stdout,stderr = client.exec_command(command)
#打印執(zhí)行結(jié)果
print stdout.readlines()
#關(guān)閉SSHClient
client.close()
法2
#實(shí)例化SSHClient
client = paramiko.SSHClient()
#自動(dòng)添加策略惭等,保存服務(wù)器的主機(jī)名和密鑰信息
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#連接SSH服務(wù)端珍手,以用戶名和密碼進(jìn)行認(rèn)證
client.connect(ip,username=user,password=passwd)
#實(shí)例化Transport办铡,并建立會(huì)話Session
ssh_session = client.get_transport().open_session()
if ssh_session.active:
ssh_session.exec_command(command)
print ssh_session.recv(1024)
client.close()
迭代器
TIM截圖20180723113737.png
有限序列變無限序列
from itertools import cycle
counter2 = cycle(['a','b','c'])
for i in range(1,10):
print(counter2.__next__())
無限序列
from itertools import count
counter = count(start=2)
print(hasattr(counter,'__next__'))
print(hasattr(counter,'__iter__'))
for i in range(1,10):
print(counter.__next__())
獲取迭代器
def foo():
for i in range(5):
yield i
g_obj = foo()
#shengchengqi hanshu
print(hasattr(g_obj,'__iter__'))
print(hasattr(g_obj,'__next__'))
print(next(g_obj))
li_obj = (i for i in range(100000)) #用()產(chǎn)生對(duì)象 里面有算法
print(li_obj)
#list(range(100000)) 延遲算法
def iter1():
for i in range(10):
yield i
g =iter1()
g1=(i for i in g)
print(list(g1))
g2=(i for i in g1)
print(list(g2))
result:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[]