__init__方法中的变量范围?

时间:2017-02-09 21:53:59

标签: python class oop scope

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


    def findAgeGroup(self):
        if age >= 80:
            ageGroup= "old"
            print ageGroup

John= Person(95)
John.findAgeGroup

所以我的问题可能很简单。在__init__方法的上述代码中,当self.age类的新实例被实例化时,变量Person被设置?而__init__方法中的所有其他变量都放在那里,因为它们与self.age有关?例如,findAgeGroup方法age用于导出ageGroup.的值。因此,如果您在self.ageGroup方法中列出__init__的唯一时间计划从创建类的新实例时调用的self.age派生值?

1 个答案:

答案 0 :(得分:2)

在Python中,您实际上总是需要self来引用实例变量,这与Java的this

def findAgeGroup(self):
    if self.age >= 80:
        self.ageGroup = "old"
        print self.ageGroup 
   # also Python prefers snake_case: self.age_group
相关问题