【问题标题】:Variable scope in __init__ method? [closed]__init__ 方法中的变量范围? [关闭]
【发布时间】:2017-06-28 02:30:35
【问题描述】:
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__ 方法的上述代码中,当实例化Person 类的新实例时设置变量self.age? __init__ 方法中的所有其他变量都放在那里,因为它们与 self.age 相关?例如,在findAgeGroup 方法中,age 用于派生ageGroup. 的值因此,您在__init__ 方法中列出self.ageGroup 的唯一时间是如果您计划从self.age 派生值在创建类的新实例时调用?

【问题讨论】:

  • 你需要使用if self.age >= 80:(和self.ageGroup = "old"等)。
  • 1.听起来您需要继续查看 Python OOP 教程。 2. 这段代码会产生一个NameError。
  • 另请注意,在未定义的self.ageGroup = ageGroup ageGroup 和John.findAgeGroup 中,您可能是指John.findAgeGroup()
  • @Nullman 我想你刚刚回答了我的问题。所以self.ageGroup 根本不应该在__init__ 方法中?因为在创建person 的新实例时没有定义它?
  • 我投票决定将此问题作为离题结束,因为 SO 不是教程服务。

标签: python class oop scope


【解决方案1】:

在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 2021-05-18
    • 1970-01-01
    • 2017-06-02
    • 2012-05-18
    • 1970-01-01
    相关资源
    最近更新 更多