如何从python中的另一个函数访问和更改(class)init方法属性?

2024-04-19 05:07:09 发布

您现在位置:Python中文网/ 问答频道 /正文

最近我尝试访问__init__方法属性,以更改其值并从另一个函数自动重新计算某些属性。你知道吗

我试过一些基本的方法,但没有成功地得到我想要的。这是问题代码:

class Square():
     def __init__(self, length, width):
         self.length = length
         self.width = width

     @property
     def Area(self):
         return self.length * self.width

A1 = Square(length=3, width=3) ## made an object
print(A1.Area) #9

def check():
    a = []
    b = [1,3,2]
    t = [100,20,23]
    d = [0.1]
    c = 4
    for i in d:
        c += 6
        d += [0.1]
        if A1.Area < 8: ## eg. if A1.length=2 and A1.width=2 have been changed in the  __init__ attribute this A1.Area would be 4 and the condtion is ture and the loop break ends
            break ## here break the loop finally  if the A1.Area is altered by the conditions 
        for k in range(len(b)):
            a.append(c + b[k])
            if c + b[k] > t[2]:
                A1.length = 2## here i am trying to change the __init__ attribute
                A1.width = 2 ## here i am trying to change the __init__ attribute
                print(k)
                c = c - 6
                break
    return c

Tags: andthe方法inselfifhereinit
1条回答
网友
1楼 · 发布于 2024-04-19 05:07:09

我不知道您在check函数中真正想做什么,但以下几点对我来说很好:

>>> class Square():
...      def __init__(self,length, width):
...          self.length=length
...          self.width=width
...      @property
...      def area(self):
...          return(self.length*self.width)
...
>>> a=Square(2,3)
>>> a.length
2
>>> a.area
6
>>> a.length=4
>>> a.length
4
>>> a.area
12
>>> for i in range(4):
...   a.length = i
...   print a.area
...
0
3
6
9

相关问题 更多 >