2 回答

TA貢獻1777條經驗 獲得超10個贊
namedtuples
:
返回一個名為 typename 的新元組子類。新的子類用于創建類似元組的對象,這些對象具有可通過屬性查找訪問的字段,并且是可索引和可迭代的。子類的實例還有一個有用的文檔字符串(帶有 typename 和 field_names)和一個有用的repr () 方法,它以 name=value 格式列出元組內容。
與typing
:
該模塊支持 PEP 484 和 PEP 526 指定的類型提示。最基本的支持包括類型 Any、Union、Tuple、Callable、TypeVar 和 Generic。有關完整規范,請參閱 PEP 484。有關類型提示的簡化介紹,請參閱 PEP 483。
鍵入 NamedTuples 只是原始 namedtuples 的包裝。
2.需要實例才能使用instancemethods:
兩者的修復:
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)

TA貢獻1824條經驗 獲得超6個贊
cnct
是一種需要對象實例的方法。在這里,您嘗試將其稱為類方法。如果這是你想要的,你應該使用裝飾器:
@classmethod def cnct(cls, u): ...
添加回答
舉報