【问题标题】:How to use a global variable for all class methods in Python?如何为 Python 中的所有类方法使用全局变量?
【发布时间】:2017-01-12 00:53:54
【问题描述】:
  • 我有一个Person 类,它拥有一个age 属性,现在我需要让它在Person 类内的所有方法中都可以访问,以便所有方法都能正常工作

    李>
  • 我的代码如下:

class Person:
    #age = 0
    def __init__(self,initialAge):
        # Add some more code to run some checks on initialAge
        if(initialAge < 0):
            print("Age is not valid, setting age to 0.")
            age = 0
        age = initialAge

    def amIOld(self):
        # Do some computations in here and print out the correct statement to the console
        if(age < 13):
            print("You are young.")
        elif(age>=13 and age<18):
            print("You are a teenager.")
        else:
            print("You are old.")

    def yearPasses(self):
        # Increment the age of the person in here
        Person.age += 1 # I am having trouble with this method

t = int(input())
for i in range(0, t):
    age = int(input())         
    p = Person(age)  
    p.amIOld()
    for j in range(0, 3):
        p.yearPasses()       
    p.amIOld()
    print("")
  • yearPasses() 应该将age 增加 1,但现在调用时它什么也不做

  • 如何对其进行调整以使其发挥作用?

【问题讨论】:

  • @PM2Ring 实际上,我是对象编程的新手......甚至不知道如何描述我的问题(逃跑
  • OOP 一开始有点陌生,但就像编程中的任何事情一样,只要练习足够多,很快就会熟悉。

标签: python class object methods instance


【解决方案1】:

您需要age 作为 Person 类的实例属性。为此,您可以使用self.age 语法,如下所示:

class Person:
    def __init__(self, initialAge):
        # Add some more code to run some checks on initialAge
        if initialAge < 0:
            print("Age is not valid, setting age to 0.")
            self.age = 0
        self.age = initialAge

    def amIOld(self):
        # Do some computations in here and print out the correct statement to the console
        if self.age < 13:
            print("You are young.")
        elif 13 <= self.age <= 19:
            print("You are a teenager.")
        else:
            print("You are old.")

    def yearPasses(self):
        # Increment the age of the person in here
        self.age += 1 

#test

age = 12
p = Person(age)  

for j in range(9):
    print(j, p.age)
    p.amIOld()
    p.yearPasses()    

输出

0 12
You are young.
1 13
You are a teenager.
2 14
You are a teenager.
3 15
You are a teenager.
4 16
You are a teenager.
5 17
You are a teenager.
6 18
You are a teenager.
7 19
You are a teenager.
8 20
You are old.

您的原始代码有类似

的语句
age = initialAge 

在它的方法中。这只是在方法中创建了一个名为age 的本地对象。此类对象在方法之外不存在,并且在方法终止时会被清除,因此下次调用该方法时,其旧值 age 已丢失。

self.age 是类实例的一个属性。该类的任何方法都可以使用self.age 语法访问和修改该属性,并且该类的每个实例都有自己的属性,因此当您创建Person 类的多个实例时,每个实例都会有自己的.age

还可以创建作为类本身属性的对象。这允许类的所有实例共享一个对象。例如,

Person.count = 0

为 Person 类创建一个名为 .count 的类属性。您还可以通过将赋值语句放在方法之外来创建类属性。例如,

class Person:
    count = 0
    def __init__(self, initialAge):
        Person.count += 1
        # Add some more code to run some checks on initialAge
        #Etc

将跟踪您的程序到目前为止创建了多少 Person 实例。

【讨论】:

  • 谢谢!这正是我被困的地方......我不知道如何在所有情况下使用相同的 age 变量以及 self 的工作原理
  • 好的,谢谢。也需要自学一些面向对象的基础知识
  • @jm33_m0 希望我添加的新信息能让事情变得更清晰。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2014-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-04
相关资源
最近更新 更多