首页 > 解决方案 > 重用在 python 类中定义的变量

问题描述

假设我定义了一个类。我有一个有趣的方法,我创建 self.x。我想以不同的方法(重用)使用 self.x。我怎么能那样做?因为我尝试了我写的东西并且没有工作。谢谢!

class test:
    def __init__(self,t):
       self.t = t
    def fun(self):
       self.x = self.t+1
    def reuse(self):
       self.y = self.x 

标签: pythonclassvariablesmethods

解决方案


您需要在__init__方法中创建所有变量。尝试这个:

class test:
    def __init__(self,t):
       self.t = t
       self.x = 0
       self.y = 0
    def fun(self):
       self.x = self.t+1
    def reuse(self):
       self.y = self.x 

推荐阅读