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

Question:

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 ?

Asked By: ulahh

||

Answers:

That error explains correctly that you do not have a class attribute called ip_range2. You need to define the class attribute first.

class Uygulama(object):
    ip_range2 = ''
    ...

then use that with self.ip_range2.

Answered By: Talkhak1313

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.

Answered By: Dorian Turba
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.