Python中,可以通过关键字class
来定义一个类。类是一种自定义数据类型,它可以包含属性(变量)和方法(函数)。下面是一个示例:
class MyClass:
def __init__(self, name):
self.name = name
def say_hello(self):
print("Hello, " + self.name + "!")
在上面的示例中,我们定义了一个名为MyClass
的类。该类有一个构造方法__init__
,它会在创建类的实例时被调用。构造方法接受一个参数name
,并将其保存在实例变量self.name
中。
另外,该类还有一个方法say_hello
,用于打印出问候消息。在方法定义中,我们使用self
来引用当前实例对象。
要使用这个类,可以创建一个类的实例,并调用其方法:
obj = MyClass("Alice")
obj.say_hello() # 输出:Hello, Alice!
通过类的实例,我们可以访问实例变量和调用方法。这是面向对象编程的基本概念。
(注:以上内容摘录自互联网人工智能大数据,因为其理论定义更官方哈哈!以下内容则为本人原创,欢迎大家指教!)
实战示例:
1 #!/usr/bin/python 2 # -*- coding: utf-8 -*- 3 4 # Filename: get_gluster_data.py 5 # CreateDate: 20230417 6 # Description: 获取glusterfs分布式存储集群性能数据 7 # ------------------------------------------------------------ 8 # Version 1.2 9 # ------------------------------------------------------------ 10 """ 11 用法: 12 python get_gluster_data.py 13 """ 14 15 import time 16 import os 17 import re 18 import commands 19 import getopt 20 import logging 21 import logging.handlers 22 import sys 23 reload(sys) 24 sys.setdefaultencoding('utf8') 25 26 LOG_FILE = "/tmp/get_gluster_data.log" 27 handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes = 1024*1024*1024, backupCount = 5) 28 fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s' 29 formatter = logging.Formatter(fmt) 30 handler.setFormatter(formatter) 31 logger = logging.getLogger('get_gluster_data') 32 logger.addHandler(handler) 33 logger.setLevel(logging.DEBUG) 34 #file_path = "/var/lib/sdsom/var/log/diamond/ops.data" 35 36 37 class storageCluster: #定义一个存储集群类 38 39 def __init__(self, data_file): #定义一个构造方法,声明类属性:集群的性能数据文件 40 self.data_file = data_file 41 42 def get_performance_data(self): #获取性能数据的方法 43 gather_cmd = "/var/lib/sdsom/venv/bin/whisper-fetch.py --from=$(date +%s -d \"-5 min\") /var/lib/sdsom/var/lib/graphite/whisper/gluster/cluster/" 44 cmd = gather_cmd + self.data_file + ".wsp | grep -v None | tail -1 | awk '{print $2}'" 45 value = commands.getoutput(cmd) ##执行shell 46 key = self.data_file 47 print key + ":" + value 48 if re.search("ops", key): #不同的性能数据进行单位换算 49 zabbix_value = float('%.2f' % float(value)) 50 print zabbix_value 51 return zabbix_value 52 elif re.search("mbps", key): 53 value = float(value)/1024/1024 54 zabbix_value = float('%.2f' % value) 55 print zabbix_value 56 return zabbix_value 57 elif re.search("latency", key): 58 value = float(value)/1000 59 zabbix_value = float('%.2f' % value) 60 print zabbix_value 61 return zabbix_value 62 63 def send_zabbix(self, key, value): #数据发送到zabbix服务端的方法 64 cmd = "/opt/product/zabbix/bin/zabbix_sender -c /opt/product/zabbix/conf/zabbix_agentd.conf -k %s -o %s "%(key,value) 65 logger.debug(cmd) #记录日志 66 status,value = commands.getstatusoutput(cmd) #执行shell 67 print ("Program Execution_code: ") + str(status) + ",",("result: ") + str(value) 68 logger.debug("%s,%s"%(str(status),value)) 69 if status==0: 70 print "%s,send to zabbix successfully!"%(cmd) 71 print (" ") 72 print ("------------------------------------------------------------") 73 logger.debug("%s,True"%(cmd)) 74 return True 75 else: 76 print "%s,send to zabbix failed!"%(cmd) 77 print (" ") 78 print ("------------------------------------------------------------") 79 logger.debug("%s,False"%(cmd)) 80 return False 81 82 def get_performance_log(self): #记录本地性能数据日志的方法 83 date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) #格式化时间 84 logdir = "/var/log/ops/" 85 if os.path.exists(logdir) is False: #判断/var/log/ops/目录是否存在,如果不存在则创建 86 os.mkdir(logdir) 87 performance_log = logdir + self.data_file + ".log" 89 with open(performance_log, 'a+') as f: 90 value = self.get_performance_data() 91 log = date + '\t' + str(value) + '\n' 92 print(log) 93 f.write(log) 94 f.close() 95 96 97 if __name__ == '__main__': 98 startTime = time.time() #脚本执行开始时间 99 data_list = [ops, read_ops, write_ops, write_mbps, read_mbps, write_latency, read_latency] #创建性能数据文件列表 100 for i in data_list: 101 storcluster = storageCluster(i).send_zabbix(key=self.data_file, value=self.get_performance_data()) #实例化类并获取性能数据并发送到zabbix服务端 102 storcluster = storageCluster(i).get_performance_log() #记录本地性能数据日志 103 #storcluster = storageCluster("ops").get_performance_data() 104 #storcluster = storageCluster("read_ops").get_performance_log() 105 endTime = time.time() #脚本执行结束时间 106 runtime = startTime - endTime 107 print(runtime) 108 print("performance_data send completed !")
本文来自博客园,作者:Albert_M,转载请注明原文链接:https://www.cnblogs.com/Albert-M/p/17644744.html