Python 获取键的值,该键是类属性的一部分

Python 获取键的值,该键是类属性的一部分,python,Python,当我试图得到“h”的值时 使用.get方法 nn = Humanoid.body.get("h") 我得到这个错误 nn=Humanoid.body.get(“h”) AttributeError:type对象“Humanoid”没有属性“body”您必须实例化类对象 human = Humanoid() human.body.get("h") 这里,body是一个实例属性,因此您需要实例化类以访问其实例属性: class Humanoid: def __init__(self):

当我试图得到“h”的值时

使用.get方法

nn = Humanoid.body.get("h")
我得到这个错误

nn=Humanoid.body.get(“h”)

AttributeError:type对象“Humanoid”没有属性“body”

您必须实例化类对象

human = Humanoid()

human.body.get("h")

这里,
body
是一个实例属性,因此您需要实例化类以访问其实例属性:

class Humanoid:
    def __init__(self):
        self.body = {"h": 1, "a": 2, "l": 2}
        self.needs = ["n"]
        self.move = False

humanoid = Humanoid()
print(humanoid.body.get("h"))
或者将实例属性转换为类属性,如:

class Humanoid:
    body = {"h": 1, "a": 2, "l": 2}

    def __init__(self):
        self.needs = ["n"]
        self.move = False

print(Humanoid.body.get("h"))

body是一个实例属性,用于实例化对象,否则将其作为类属性以另一种方式访问
class Humanoid:
    body = {"h": 1, "a": 2, "l": 2}

    def __init__(self):
        self.needs = ["n"]
        self.move = False

print(Humanoid.body.get("h"))