簡體   English   中英

Python如何從類方法調用實例方法?

[英]Python how to call instance method from class method?

我有以下代碼:

class Player():
    """Initialization examples:
            player = Player('Lebron', 'James')
            player = Player.by_id(2544)
    """
    def __init__(self, first_name, last_name):
        """Search for a given player matching first_name and last_name.

        The matching is case insensitive.
        """
        self.player = self._get_player_by_name(
            first_name.lower(), last_name.lower())

    @classmethod
    def by_id(self, player_id):
        """Search for a given player by thier nba.com player id.

        Args:
            player_id: str representation of an nba.com player id
                e.g. Lebron's player id is 2544 and his nba.com link is
                    https://stats.nba.com/player/2544/

        Intended as an alternate Player constructor.
        """
        self.player = self._get_player_by_id(str(player_id))

    def _get_player_by_id(self, player_id):
        pass

但是,在調用Player.by_id(2544) ,出現以下錯誤:

TypeError: _get_player_by_id() missing 1 required positional argument: 'player_id'

這里發生了什么? 我搜索過的大多數問題都涉及添加我已經擁有的 self 參數。

@classmethod使方法將類類型作為第一個參數,而不是特定實例。 例如,考慮以下代碼:

class C:
    @staticmethod
    def a():
        # static methods take no implicit parameters
        print("a")

    @classmethod
    def b(cls):
        # class methods implicitly take the *class object* as the first parameter
        print("b", cls)

    def c(self):
        # instance methods implicitly take the instance as the first parameter
        print("c", self)

C().a()
C().b()
C().c()

這打印

a
b <class '__main__.C'>
c <__main__.C object at 0x103372438>

請注意,按照慣例,我們使用cls而不是self作為類方法。 這只是約定——調用這個參數self並不會神奇地使它成為一個實例!

這意味着,在by_id ,當您調用self._get_player_by_id您正在調用Player._get_player_by_id - 沒有實例。 這意味着player_id最終被作為“self”傳遞,導致您看到的錯誤。

為了解決這個問題,您可能希望_get_player_by_id也是一個類方法。

by_id 是一個類方法,正如您通過使用類名調用該方法所知道的那樣。

然而,這個類方法然后調用一個實例特定的方法,

_get_player_by_id.

發生的情況是,當 _get_player_by_id 運行時,您將 player_id 作為參數提供給 self,而不是實際的 player_id。

這是有道理的,因為self引用的是實例,而不是類對象。

您需要做的是,在您的by_id方法中,您需要傳入 Player 的實例,並將其與 player_id 一起傳遞給 get_player_by_id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM