Skip to main content
 首页 » 编程设计

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

2025年05月04日16softidea

这是我的代码,它应该从类设置中打印 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()