gpt4 book ai didi

python - 无法从另一个类python访问变量

转载 作者:太空宇宙 更新时间:2023-11-04 05:39:01 26 4
gpt4 key购买 nike

这是我的代码,它应该从类设置中打印 self.cake 和 self.age。

from startup import Settings
class Profile(Settings):
def __init__(self):
super(Profile, self).__init__()

def print_settings(self):
print self.cake
print self.age

p = Profile()
p. print_settings()

其他python脚本

class Settings(object):
def __init__(self):
self.cake = 1

def number(self):
self.age = 5

但我不断得到:

AttributeError: 'Profile' object has no attribute 'age'

我需要能够从 print_settings 函数打印变量。

我该怎么办?

最佳答案

在调用print_settings 方法之前,您必须设置age 属性。

一个选项是:

p = Profile()
p.number()
p.print_settings()

关于python - 无法从另一个类python访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34709928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com