python 面向对象
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代表类的实例,而非类
类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self。
class Test:
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()
以上实例执行结果为:
<__main__.Test instance at 0x10d066878>
__main__.Test
从执行结果可以很明显的看出,self 代表的是类的实例,代表当前对象的地址,而 self.class 则指向类。
self 不是 python 关键字,我们把他换成 runoob 也是可以正常执行的:
Python内置类属性
__dict__ : 类的属性(包含一个字典,由类的数据属性组成)
__doc__ :类的文档字符串
__name__: 类名
__module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)
__bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)
Python内置类属性调用实例如下:
实例
class Person():
city = "BeiJing" # 类的数据属性
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" # 类的数据属性
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 等都成为工厂函数,它们本身就是一个类,谁调谁好使 谁调,就向谁的列表中添加
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]
静态方法
class Math():
@staticmethod
def Add(a,b):
print(a+b)
Math.Add(1,3) #调用函数应该有2个参数就传2个参数
op=Math()
# 实例也可以使,但通常静态方法都是给类用的,实例在使时丧失了自动动传参的机制
op.Add(1,4)
result:
4
5
# 需求
# 1.定义三个类:Student Teacher ClassName
# 2.可以通过 Teacher的实例,可以查询到这个对象的所有学生,还可以查询到这个对象所管理的班级
# 3.学生必须创建4个,且至少分配给两个老师,还被分别分配到了两个班级
# 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))
#对父类车进行继承
class car(Vehicle):
def __init__(self,name,brand,date,speed):
# self.name=name #法一 在子类中添加新的参数 调用父类初始化化的三种方法
# 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)
#多态
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))
#对父类车进行继承
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("保时捷","x1","070101","20km/h")
def func(obj): # 为了很好的展示多态性,还有再借个函数
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 被调用")
return self.__name
@name.setter
def name(self,__name):
print("settter 被设置了")
self.__name=__name
a = A('shark',19)
a.age =10 #可以改写age
#a.name="zhu" #不能改写 会报错
a.name="zhu"
print(a.name)
#print(a.name)
result:
settter 被设置了
getter 被调用
zhu
#反射(自省)
#模块是以.py结尾
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__) #只有实例才有name属性
print(obj.__dict__) #只有实例才有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 #导入上一个例子模块
a= getattr(cls,'A') #通过反射得到A这个类
print(a)
obj1 = a("yang",29)
print(getattr(obj1,'name'))
print(isinstance(obj1,a))
# print(globals())
导入包里面的模块
# from pak import host,main #法一 pak是个文件夹里面有host.py,main.py
import sys # 模块搜索路径存储在 system 模块的 sys.path 变量中
import pak.host #法二
import pak.main #法二
print(sys.path)
print(pak.host.host)
pak.main.connection("zz",80,"gg","root")
导入模块
from conf import settings #可以将settins.py放到conf目录里
host_info={}
from importlib import import_module #重点 以前没写出来卡住了
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)
魔术方法
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)
抽象类 用于其他类继承他 被人继承他就得去实现他的方法
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 环境要装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
#实例化SSHClient
client = paramiko.SSHClient()
#自动添加策略,保存服务器的主机名和密钥信息
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#连接SSH服务端,以用户名和密码进行认证
client.connect(ip,username=user,password=passwd)
#打开一个Channel并执行命令
stdin,stdout,stderr = client.exec_command(command)
#打印执行结果
print stdout.readlines()
#关闭SSHClient
client.close()
法2
#实例化SSHClient
client = paramiko.SSHClient()
#自动添加策略,保存服务器的主机名和密钥信息
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#连接SSH服务端,以用户名和密码进行认证
client.connect(ip,username=user,password=passwd)
#实例化Transport,并建立会话Session
ssh_session = client.get_transport().open_session()
if ssh_session.active:
ssh_session.exec_command(command)
print ssh_session.recv(1024)
client.close()
迭代器
有限序列变无限序列
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)) #用()产生对象 里面有算法
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]
[]