Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use any obtained variable from a function in other functions in Python classes?

I am trying to use one variable obtained from one function in other function. However , it gives error. Let me explain it wih my code.

class Uygulama(object):
    
    def __init__(self):
        self.araclar()
        self.refresh()
        self.gateway_find()
    def refresh(self):
    
    self.a, self.b = srp(Ether(dst="FF:FF:FF:FF:FF:FF") / ARP(pdst=self.ip_range2), timeout=2,     iface="eth0",
               retry=3)

     #There are unrelated codes here

    def gateway_find(self):
    
    #Find ip any range in which you conncet:
    self.ip_range=conf.route.route("0.0.0.0")[1]
    self.ip_range1=self.ip_range.rpartition(".")[0]
    self.ip_range2=self.iprange_1+".0/24"

When , run the foregoing codes , i get this error AttributeError: ‘Uygulama’ object has no attribute ‘ip_range2’

How can i use such variable which are obtained from other function in the other function. How can i fix my problem ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Call order of init functions

Place function that define attribute first

In the __init__ function, you call refresh, who use (need) ip_range2 before gateway_find who create the attribute and set a value to it. Swap the two lines, you should be fine.

    def __init__(self):
        self.araclar()
        self.gateway_find()  # gateway_find will set the ip_range attribute
        self.refresh()  # So refresh function will be able to access it

Usually, we place init functions first, then function that will call post-init processes like refresh.

Class attribute default value

Alternatively, you can define a default value for ip_range2 like this:

class Uygulama(object):
    ip_range2 = None

    def __init__(self):
        self.araclar()
        self.refresh()
        self.gateway_find()

    def refresh(self):
        self.a, self.b = srp(Ether(dst="FF:FF:FF:FF:FF:FF") / ARP(pdst=self.ip_range2), timeout=2, iface="eth0", retry=3)

Be aware that such default value is shared with all other instances of the class if not redefined in __init__, so if it’s a mutable (like a list), it might create really weird bugs.

Usually, prefer defining value in the __init__ like you do with the gateway fct.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading