Python Forum
first try with python class, suggestion for improvement please
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
first try with python class, suggestion for improvement please
#11
Comment lines 23 and 24.
Reply
#12
Thanks, something is going wrong and not able to understand, if I am accessing class in loop and get class method variable values.

from easysnmp import Session
import time
from datetime import datetime
import datetime
#from collections import namedtuple
  
class fan:
    """\
    this class to collect information about fan speed and fan status
    final output will be like below
    -------------------------------------------------------------------------------
    Environment Information
 
    Number of fan trays               : 1
    Number of fans                    : 3
 
    Fan tray number                   : 1
       Speed                           : half speed
       Status                          : up
   -------------------------------------------------------------------------------"""
     
     
     
    #convert oid number in to fan speed , str oid value
    # dict for FanSpeed oid output value    
    fan_speed =  { 0:'Not Applicable',
                  1:'Unknown',
                  2:'Half Speed',
                  3:'Full Speed',
                  4:'Low Speed'
                }
    #convert oid output in fan status, str oid value 
    #Dict for Fanstatus oid output values
    fan_status = { '1':'Unknown',
                  '2':'Fan Removed',
                  '3':'Up',
                  '4':'Fail',
                  '5':'Out of Service'
                }
        
    def __init__(self,host,community,version,timeout,value):
        self.host = host
        self.community = community
        self.version = version
        self.timeout = timeout
    
    #@classmethod
    # return fan speed and parameter will be oid value
    def get_fan_speed(self, value):
        return self.fan_speed.get(value,"other")
             
    #return fan status, parameter will be oid value
    def get_fan_status(self,value):
        return self.fan_status.get(value,"other")
  
   
    def get_fan_details(host):
           # establish easysnmp session with host
           session = Session(hostname=host, community="cacti", version=2,timeout=5)
           # start bulkwalking snmp oids 
           tmnxChassisNumFanTrays = session.bulkwalk('1.3.6.1.4.1.6527.3.1.2.2.1.3.1.10')
           NumFanTrays = str(u"{value}".format(value=tmnxChassisNumFanTrays[0].value))
           tmnxChassisNumFans = session.bulkwalk('1.3.6.1.4.1.6527.3.1.2.2.1.3.1.11')
           NumFans = str(u"{value}".format(value=tmnxChassisNumFans[0].value))
           tmnxChassisFanSpeed = session.bulkwalk('1.3.6.1.4.1.6527.3.1.2.2.1.4.1.3')
           FanSpeed = str(u"{value}".format(value=tmnxChassisFanSpeed[0].value))
           tmnxChassisFanOperStatus = session.bulkwalk('1.3.6.1.4.1.6527.3.1.2.2.1.4.1.2')
           FanOperStatus = str(u"{value}".format(value=tmnxChassisFanOperStatus[0].value))
           return NumFanTrays, NumFans, FanSpeed,FanOperStatus
           # returning output as str
if __name__ == "__main__":
        hosts = ['10.124.209.66','10.124.209.74']
        for host in hosts:
            #print(host)
            try:
                fandetails  = fan.get_fan_details(host)
            except:
                break
            print(fandetails) # able to print
            NumFanTrays = fandetails[0] # able to print
            NumFans = fandetails[1] # able to print
            #Fanspeed = fandetails[2]
            #FanStatus = fandetails[3]
            #print(type(FanStatus)) 
            Fanspeed = fan.get_fan_speed(str(2))
            FanStatus = fan.get_fan_status(str(2))
            print('Num Of Tray:{} Number of Fans: {} Fan Speed:{} Fan Status:{}'.format(NumFanTrays,NumFans,Fanspeed,FanStatus))
able to print fandetails, however not able to access dict values

Output:
('1', '3', '2', '3')
Error:
Traceback (most recent call last): File "testclass3.py", line 87, in <module> Fanspeed = fan.get_fan_speed(str(2)) TypeError: get_fan_speed() missing 1 required positional argument: 'value'
Reply
#13
Here is a simple example to show what's happening in your case
>>> class A:
...     def get_spam(self, ham):
...         return 3.14
... 
>>> A.get_spam()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: get_spam() missing 2 required positional arguments: 'self' and 'ham'
>>> a = A() # <--- Creating a class INSTANCE
>>> a.get_spam()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: get_spam() missing 1 required positional argument: 'ham'
>>> a.get_spam('egg')
3.14
Reply
#14
thanks, got some idea... will let you know.
Reply
#15
thanks,Gribouillis and all admin and moderator

Changed code, its working for me, but having small question, how can I can parse data inside class and return dict.

from easysnmp import Session
import time
from datetime import datetime
import datetime
#from collections import namedtuple
  
class fan:
    """\
    this class to collect information about fan speed and fan status
    final output will be like below
    -------------------------------------------------------------------------------
    Environment Information
 
    Number of fan trays               : 1
    Number of fans                    : 3
 
    Fan tray number                   : 1
       Speed                           : half speed
       Status                          : up
   -------------------------------------------------------------------------------"""
     
     
     
    #convert oid number in to fan speed , str oid value
    # dict for FanSpeed oid output value    
    fan_speed =  { 0:'Not Applicable',
                  1:'Unknown',
                  2:'Half Speed',
                  3:'Full Speed',
                  4:'Low Speed'
                }
    #convert oid output in fan status, str oid value 
    #Dict for Fanstatus oid output values
    fan_status = { '1':'Unknown',
                  '2':'Fan Removed',
                  '3':'Up',
                  '4':'Fail',
                  '5':'Out of Service'
                }
        
    def __init__(self,host,community,version,timeout):
        self.host = host
        self.community = community
        self.version = version
        self.timeout = timeout
    
    def get_fan_details(self):
           # establish easysnmp session with host
           session = Session(hostname=self.host, community='cacti', version=2,timeout=5)
           # start bulkwalking snmp oids
           tmnxChassisNumFanTrays = session.bulkwalk('1.3.6.1.4.1.6527.3.1.2.2.1.3.1.10')
           NumFanTrays = str(u"{value}".format(value=tmnxChassisNumFanTrays[0].value))
           tmnxChassisNumFans = session.bulkwalk('1.3.6.1.4.1.6527.3.1.2.2.1.3.1.11')
           NumFans = str(u"{value}".format(value=tmnxChassisNumFans[0].value))
           tmnxChassisFanSpeed = session.bulkwalk('1.3.6.1.4.1.6527.3.1.2.2.1.4.1.3')
           FanSpeed = str(u"{value}".format(value=tmnxChassisFanSpeed[0].value))
           tmnxChassisFanOperStatus = session.bulkwalk('1.3.6.1.4.1.6527.3.1.2.2.1.4.1.2')
           FanOperStatus = str(u"{value}".format(value=tmnxChassisFanOperStatus[0].value))
           # returning dict
           return {
                   'NumOfFantrays':NumFanTrays,
                   'NumofFans':NumFans,
                   'FanSpeed':FanSpeed,
                   'FanStatus':FanOperStatus
                  }
           """ how can I return dict value from this class... 
               like
               return {
                   'NumOfFantrays':NumFanTrays,
                   'NumofFans':NumFans,
                   'FanSpeed':fan.get_fan_speed(FanSpeed),
                   'FanStatus':fan.fan_status.get(FanOperStatus)
                  }
           """
    
    # return fan speed and parameter will be oid value
    def get_fan_speed(self, value):
        return self.fan_speed.get(value,"other")
         
    #return fan status, parameter will be oid value
    def get_fan_status(self,value):
        return self.fan_status.get(value,"other")
  
           
if __name__ == "__main__":
        a = fan('10.124.209.66','cacti',2,5)
        data = a.get_fan_details()
        for item in data.items():
            print(item)
current out put

Output:
'NumOfFantrays', '1') ('NumofFans', '3') ('FanSpeed', '2') ('FanStatus', '3')
expected output

Output:
('NumOfFantrays', '1') ('NumofFans', '3') ('FanSpeed', 'Half Speed') ('FanStatus', 'Up')
Reply
#16
I don't understand the output that you want. Obviously the method already returns a dict.
Reply
#17
your def get_fan_details() method does not use the other two methods def get_fan_speed() and get_fan_status():

return {
                   'NumOfFantrays':NumFanTrays,
                   'NumofFans':NumFans,
                   'FanSpeed':self.get_fan_speed(FanSpeed),
                   'FanStatus':self.get_fan_status(FanOperStatus)
                  }
if you are not able to debug soemthing like this, better read again some class basics tutorial
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#18
(Oct-27-2019, 05:06 PM)Gribouillis Wrote: I don't understand the output that you want. Obviously the method already returns a dict.

but i want return dict values from class itself, instead of converting outof class.
Reply
#19
Thanks, Yoriz,Gribouillis,ichabod801,buran

got some knowledge on Class, method.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Can you give me some suggestion about PCEP Newbie1114 0 1,016 Oct-14-2021, 03:02 PM
Last Post: Newbie1114
  instagram followers name without suggestion for you jacklee26 1 3,157 Oct-02-2021, 04:57 AM
Last Post: ndc85430
  Random coordinate generator speed improvement saidc 0 2,047 Aug-01-2021, 11:09 PM
Last Post: saidc
  Python Dev suggestion: Combining line-wrap with comments inside functions NikoNiels 2 1,724 Sep-26-2020, 07:45 PM
Last Post: bowlofred
  Function Improvement Santino 1 1,796 May-23-2020, 03:30 PM
Last Post: jefsummers
  Name Mashup Program Improvement in Python rhat398 3 2,558 Apr-05-2020, 12:09 PM
Last Post: perfringo
  Optimization suggestion Julia 2 1,723 Mar-29-2020, 12:02 PM
Last Post: Julia
  Need suggestion how to handle this error farrukh 1 2,252 Dec-21-2019, 03:21 PM
Last Post: DeaD_EyE
  Python Based Data QA Automation tool suggestion Sonia567 1 1,989 Nov-19-2019, 04:46 PM
Last Post: Larz60+
  coding improvement tips vaisesumit29 1 1,801 Mar-10-2019, 05:09 PM
Last Post: stullis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020