Reputation: 69
Recently I was trying to access an __init__
method attribute to change its values and recalculate some properties automatically from another function.
I have tried some basic approaches and did not succeed to obtain what I wanted. This is the code in question:
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
Upvotes: 0
Views: 412
Reputation: 16556
I don't know what you really are trying to do in your check function but the following works ok for me:
>>> 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
Upvotes: 1