Skip to content
Advertisement

Python best practices — can I set an object attribute to call a class method?

I am building a tool to query all DNS records for a hostname. Each hostname will create a ScanObject object, which will call another module to do the queries upon instantiation.

I create class methods so that I can just pull records I need instead of all the records. Therefore, these methods need to refer to the dictionary that contains ALL the DNS records (self.current_dns_record). When I use methods like get_txt_records() to refer to self.current_dns_record, will it make call query_dns() again or just used the saved result?

I would also appreciate any generic feedback on the code architecture + code inefficiencies. This is my first time doing OOP Python and not sure if I’m doing this correctly.

Semi-psuedocode and simplified:

from resolvedns import resolvedns # custom module

    class ScanObject:
        def __init__(self, hostname):
            self.hostname = hostname
            self.current_dns_record = query_dns()

        def query_dns(self):
            response = resolvedns(self.hostname)
            return response 

        def get_txt_records(self):
            txt_records = self.current_dns_record['TXT']
            return txt_records

        def get_ns_records(self):
            ns_records = self.current_dns_record['NS']
            return ns_records

        def get_summary(self):
            return {
                "hostname": self.hostname,
                "txt_record": get_txt_records(),
                "ns_record": get_ns_records()
            }

Sample output, simplified + abbreviated:

>>> result = ScanObject("google.com")
>>> print(result.get_ns_records())
ns2.google.com
ns3.google.com
>>> print(result.get_summary())
{
    'hostname': 'google.com',
    'txt_record': ['v=spf1 include:_spf.google.com ~all',
                  '....etc....'],
    'ns_record': ['ns2.google.com', 
                 'ns3.google.com']
}

Advertisement

Answer

will it make call query_dns() again or just used the saved result?

If you look at the code, the only place where query_dns() is called is in __init__ which is only called once, on instantiation of the class. So the query_dns() will only be called when you instantiate the class.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement