亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在函數的類之外使用靜態 NamedTuples 變量

在函數的類之外使用靜態 NamedTuples 變量

開心每一天1111 2022-04-23 21:56:59
我正在使用 NamedTuple 來定義要使用 telnetlib 連接的服務器。然后我創建了一個類,它定義了與服務器的連接,在類中包含服務器詳細信息和連接方法。然后在課堂之外,我想將連接方法與服務器的 NamedTuple 一起用作連接憑據。但是,我不斷收到連接方法缺少 NamedTuple 參數的錯誤。我嘗試將 NamedTuple 拉到類之外,嘗試將 Namedtuple 放在類的 init 方法中。似乎沒有任何效果。這是我的代碼:import telnetlibfrom typing import NamedTupleclass 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'
查看完整描述

2 回答

?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

1.您可能想使用集合中的命名元組- 不輸入

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)


查看完整回答
反對 回復 2022-04-23
?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

cnct是一種需要對象實例的方法。在這里,您嘗試將其稱為類方法。如果這是你想要的,你應該使用裝飾器:

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


查看完整回答
反對 回復 2022-04-23
  • 2 回答
  • 0 關注
  • 97 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號