在函数中 class 之外使用静态 NamedTuples 变量

Using static NamedTuples variables outside of class in a function

我正在使用 NamedTuple 来定义我想使用 telnetlib 连接到的服务器。 然后我创建了一个 class 来定义与服务器的连接,在 class 中包含服务器详细信息和连接方法。 然后在 class 之外,我想使用服务器的 NamedTuple 作为连接凭证的连接方法。但是我不断收到连接方法缺少 NamedTuple 参数的错误。

我尝试将 NamedTuple 拉到 class 之外,尝试将 Namedtuple 放在 class 的 init 方法中。似乎没有任何效果。

这是我的代码:

import telnetlib
from typing import NamedTuple

class Unit(NamedTuple):
    name: str
    ip: str
    port: str

    def printunit(self, unit):
        print(unit.name)
        print(unit.ip)
        print(unit.port)

class TnCnct:
    Server1 = Unit("Server1", "1.1.1.1", "23")
    Server2 = Unit("Server2", "2.2.2.2", "23")
    Server3 = Unit("Server3", "3.3.3.3", "23")

    def __init__(self):
        pass

    def cnct(self, u):
        try:
            tn = telnetlib.Telnet(u.ip, u.port, 10)
            tn.open(u.ip, u.port)
            tn.close()
            response = u.name + " " + "Success!"
        except Exception as e:
            response = u.name + " " + "Failed!"
            print(e)
        finally:
            print(response)


TnCnct.cnct(TnCnct.Server1)

我得到的确切错误:

TypeError: cnct() missing 1 required positional argument: 'u'

cnct 是一种需要对象实例的方法。在这里您尝试将其称为 class 方法。 如果那是你想要的,你应该使用装饰器:

    @classmethod
    def cnct(cls, u):
        ...

1.您可能想使用 namedtuples from collections - not typing:

namedtuples:

Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful repr() method which lists the tuple contents in a name=value format.

对比typing

This module supports type hints as specified by PEP 484 and PEP 526. The most fundamental support consists of the types Any, Union, Tuple, Callable, TypeVar, and Generic. For full specification please see PEP 484. For a simplified introduction to type hints see PEP 483.

键入的 NamedTuples 只是对原始 namedtuple 的包装。

2。您需要实例才能使用实例方法:

两者的修复:

import telnetlib
from collections import namedtuple

def printunit(self, unit):
    print(unit.name)
    print(unit.ip)
    print(unit.port)

Unit = namedtuple("Unit","name ip port")
Unit.printunit = printunit 

class TnCnct:
    Server1 = Unit("Server1", "1.1.1.1", "23")
    Server2 = Unit("Server2", "2.2.2.2", "23")
    Server3 = Unit("Server3", "3.3.3.3", "23")

    def __init__(self):
        pass

    def cnct(self, u):
        try:
            tn = telnetlib.Telnet(u.ip, u.port, 10)
            tn.open(u.ip, u.port)
            tn.close()
            response = u.name + " " + "Success!"
        except Exception as e:
            response = u.name + " " + "Failed!"
            print(e)
        finally:
            print(response)

# create a class instance and use the cnct method of it 
connector = TnCnct()
connector.cnct(TnCnct.Server1)

实例与class(methods/variables)的区别详见f.e。这里:

  • What is the difference between class and instance attributes?
  • What is the difference between class and instance variables?
  • method objects vs function objects , Python class instances vs class