python - 如果 __init__ 中未定义该属性,则显示该类的属性?

标签 python class attributes instance

class MyClass:

def __init__(self,n):
    self.x = n

def set_y(self):
    self.y = self.x * 2

obj = MyClass(2)
obj.set_y
obj.__dict__

输出:

{'x': 2}
<小时/>

我的问题是,虽然实例方法set_y称为 y obj.__dict__ 不显示。是不是因为y未在 __init__ 内定义?

最佳答案

由于您忘记了括号,因此未调用方法set_y

应该是:

obj.set_y()

关于python - 如果 __init__ 中未定义该属性,则显示该类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52025639/

相关文章:

python - python程序可以通过哪些方式终止而不抛出异常?

用于在电子邮件中嵌入图像的 php 库

c++ - 错误: 'operator=' 不匹配(操作数类型为 'std::map<int, double>::iterator

php - 如何使用正则表达式获取所有属性?

attributes - Maven Eclipse插件classpathContainer是否具有属性?

python - 分组并查找属于 n 个唯一最大值的所有值

python - mysql.connector.errors.ProgrammingError : Error in SQL Syntax

python - Django - 一个 View ,多个 URL?

c++ - 派生带/不带参数的基类函数

attributes - 如何从 thingsboard 服务器端访问属性