Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python如何从类方法调用实例方法?_Python - Fatal编程技术网

Python如何从类方法调用实例方法?

Python如何从类方法调用实例方法?,python,Python,我有以下代码: 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_

我有以下代码:

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
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()
但是,当调用
Player.by_id(2544)
时,我得到以下错误:

TypeError:\u get\u player\u by\u id()缺少1个必需的位置参数:“player\u id”


这是怎么回事?我搜索的大多数问题都只涉及添加自变量,我已经有了自变量。

by\u id是一个类方法,您可以使用类名调用该方法

但是,该类方法随后调用一个特定于实例的方法

_get_player_by_id.
发生的情况是,当运行_get_player_by_id时,您将player_id作为参数参数提供给self,而不是实际的player_id

这是有意义的,因为self引用的是实例,而不是类对象


您需要做的是,在您的by_id方法中,您需要传入播放器的实例,并将其与播放器id一起传入get_Player_by_id

@classmethod
使该方法将类类型作为第一个参数,而不是特定实例。例如,考虑下面的代码:

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
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>
a
B
C
注意,按照惯例,我们对类方法使用
cls
而不是
self
。这只是惯例-调用此参数
self
不会神奇地使其成为一个实例

这意味着,在
by\u-id
中,当您调用
self.\u-get\u-player\u-by\u-id
时,您正在调用
player.\u-get\u-player\u-by\u-id
——没有实例。这意味着
player\u id
最终被传递为“self”,从而导致您看到的错误


要解决这个问题,您可能希望
\u get\u player\u by\u id
也成为一个类方法。

这里有一件事可以显著提高您的清晰度:由
by\u id
接收的第一个参数不是
player
的实例,所以不要称它为
self
。它是
Player
本身(或其子类),应该命名为
cls
,以表明它是一个类,而不是一个实例。除非您将实例作为第一个参数传递,否则尝试对类调用实例方法是无效的,而您没有这样做。您介意添加代码修复吗?我不太明白。我还根据@ShadowRanger的评论将by_id的第一个参数切换为cls