[英]Get the value of a key that its part of the properties of a class
When i try to get the value of "h"当我尝试获取“h”的值时
class Humanoid():
def __init__(self):
self.body = {"h":1, "a":2, "l":2}
self.needs = ["n"]
self.move = False
Using the.get method使用.get方法
nn = Humanoid.body.get("h")
i get this error我得到这个错误
nn = Humanoid.body.get("h") AttributeError: type object 'Humanoid' has no attribute 'body'
Here, body
is an instance attribute so you need to instantiate the class to access its instance attributes:这里,
body
是一个实例属性,因此您需要实例化 class 以访问其实例属性:
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"))
Or convert the instance attribute to a class attribute, like:或者将实例属性转换为 class 属性,例如:
class Humanoid:
body = {"h": 1, "a": 2, "l": 2}
def __init__(self):
self.needs = ["n"]
self.move = False
print(Humanoid.body.get("h"))
You have to instantiate the class object.您必须实例化 class object。
human = Humanoid()
human.body.get("h")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.