简体   繁体   English

方法中的Python类属性

[英]Python class attributes inside a method

Consider the following code, I want you to explain why the code doesn't work because I have seen others to assign the class attributes outside __init__ and call the attributes in one method from another, what is wrong with mine. 考虑下面的代码,我想让您解释为什么代码不起作用,因为我看到其他人在__init__之外分配类属性,并从另一个方法中调用该属性,我的问题是什么。 The following three prints all result error saying the class has no attributes whatsoever. 下面的三个打印所有结果错误,表明该类没有任何属性。

class Person(object):
    def __init__(self, age, height):
        self.age = age
        self.height = height

    def weight_kg(self):
        self.weight = 60

    def ratio_kg2height(self):
        self.ratio = self.weight / self.height
        return self.ratio


mike = Person(23, 170)
print mike.weight
print mike.ratio_kg2height()
print mike.ratio

You are not defining the weight attribute in the __init__ method, since you dont call weight_kg method before accesing the attribute it is not available. 您没有在__init__方法中定义weight属性,因为您没有在访问该属性前调用weight_kg方法。

You have some options here, the basic one is to initialize it first, you can simply call your methods in the __init__ method: 您在这里有一些选择,基本的选择是首先对其进行初始化,您可以简单地在__init__方法中调用您的方法:

class Person(object):
    def __init__(self, age, height):
        self.age = age
        self.height = height
        self.weight_kg()
        self.ratio_kg2height()

    ...

Here you have a live example 这里有一个现场例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM