一.定义
类与对象是面向对象编程的两个主要方面。
类(Class)能够创建一种新的类型(Type).
对象(Object)就是类的实例(Instance)。
属性(Attribute):
类的变量叫做字段(Field)
类变量(Class variable)是共享的(Shared)——它们可以被属于该类的所有实例访问。
对象变量(Object variable)由类的每一个独立的对象或实例所拥有。
当一个对象变量与一个类变量名称相同时,类变量将会被隐藏。
类的函数叫做方法(Method)
二.类中方法的变量互相调用:
将变量命名为self.variable
三.实例
class Connection(object):
'''
a connection to abox
'''
username = user #类变量
def __init__(self, ip, username, password):
'''
@summary: initialize Connection
'''
self.ip = ip #对象变量
self.password = password
def connect_to_server(self):
'''
@summary: create a ssh connection
'''
logging.info("connect to {}".format(self.ip))
paramiko.util.log_to_file('{}/syslogin_algomachine.log'.format(LOCAL_USER_PATH))
self.ssh = paramiko.SSHClient() #self.ssh可以在其他方法中被调用
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(hostname=self.ip, username=Connection.username, password=self.password)
def disconnect(self):
self.ssh.close()
def exec_command(self, command):
'''
@summary: execute command
@param command: executing command
@return: the stdout of command
'''
logging.info("execute command: {}".format(command))
stdin, stdout, stderr = self.ssh.exec_command(command)
logging.info("stdout: {}".format(stdout.read()))
if stderr != "":
logging.warning("stderr: {}".format(stderr.read()))
return stdout.read()
#实例化类
connection1 = Connection(ip, username, password)
connection1.connect_to_server()
connection1.exec_command("<command>")
connection1.disconnect()