Ошибка «Объект не вызывается», если я указываю параметр при попытке получить значение - PullRequest
0 голосов
/ 14 октября 2019

Когда я пытаюсь получить значение свойства и включить параметр, я получаю сообщение об ошибке «объект не может быть вызван».

Когда я получаю значение, я хочу дополнительно указать «обновить»msgstr "как Истина, чтобы заставить значение быть повторно изученным от моего хоста вместо использования значения, сохраненного в моей переменной. Например, если я скажу a = x.host_name(refresh=True), я хочу, чтобы имя хоста извлекалось из хоста, а не извлекалось из переменной _host_name.

#!/usr/local/bin/python3.7

import netaddr

"""
test.py - Used for testing

"""


class Host():
    """
    Represents a Host device

    Attributes:
        host_name: str
            Name of host
        manage_address: IP
            Managment IP address of the host
    """

    def __init__(self, host_name="", manage_address=netaddr.IPAddress("0.0.0.0")):
        """
        The constructor for the Host class.

        Parameters:
            host_name: str
                Host name of the host
            manage_address: ip
                Management IP address of this host
        """
        self._host_name = host_name
        self._manage_address = manage_address

    @property
    def host_name(self, refresh=False):
        """
        The host name configured for this host device

        Paramters:
            refresh: bool
                Should we relearn the hostname if we already know it?

        Returns: str
            Host name defined on the host
        """

        if refresh:
            # TODO: Get hostname from the host
            pass

        return self._host_name

    @host_name.setter
    def host_name(self, host_name):
        """
        Set the host name of the host

        Parameters
            host_name: str
                The host name to configure on the host

        Returns: None
        """
        self._host_name = host_name

    @property
    def manage_address(self, refresh=False):
        """
        The IP address to manage the host

        Paramters:
            refresh: bool
                Should we relearn the IP address if we already know it?

        Returns: IP
            Management IP address of the host
        """

        if refresh:
            # TODO: Get management IP address from the host
            pass

        return self._manage_address

    @manage_address.setter
    def manage_address(self, manage_address):
        """
        Set the management IP address of the host

        Parameters
            manage_address: IP
                The management IP address of the host

        Returns: None
        """
        self._manage_address = manage_address


if __name__ == '__main__':

    # A host object
    h = Host()
    h.host_name = "myhost.com"

    print(h.host_name)   # Works
    print(h.host_name(refresh=True))   # str object is not callable error
    print((str(h.manage_address(refresh=True))))   # IPAddress object is not callable error

Я предполагаю, что мне не разрешено передавать параметрпри получении значения из свойства ... но если это так, как мне получить значение условно?

1 Ответ

0 голосов
/ 14 октября 2019

Вот то, что я придумала в качестве решения:

#!/usr/local/bin/python3.7

import netaddr

"""
test.py - Used for testing

"""


class Host():
    """
    Represents a Host device

    Attributes:
        host_name: str
            Name of host
        manage_address: IP
            Managment IP address of the host
    """

    def __init__(self, host_name=None, manage_address=None):
        """
        The constructor for the Host class.

        Parameters:
            host_name: str
                Host name of the host
            manage_address: ip
                Management IP address of this host
        """
        self._host_name = host_name
        self._manage_address = manage_address

    def host_name(self, refresh=False, host_name=None):
        """
        Sets and returns the host name of the host

        Parameters:
            refresh: bool
                Should we learn the value from the host even though we already know it?
            host_name: str
                Host name of the host

        Returns: str
            The host name of the host
        """
        if host_name is not None:
            self._host_name = host_name
        elif refresh or self._host_name is None:
            # TODO: Get hostname from host
            self._host_name = "thehost.com"   # Temporary

        return self._host_name

    def manage_address(self, refresh=False, manage_address=None):

        if manage_address is not None:
            self._manage_address = manage_address
        elif refresh or self._manage_address is None:
            # TODO: Get management IP address from the host
            self._manage_address = netaddr.IPAddress("127.0.0.1")   # Temporary

        return self._manage_address

if __name__ == '__main__':

    # A host object
    h = Host()
    h.host_name(host_name="myhost.com")

    print(h.host_name())   # Works
    print(h.host_name(refresh=True))
    print(h.manage_address(refresh=True))
...