Reputation: 1
I have a class A() include some method:
class A(self):
def __init__ (self, x1, x2):
self.x1 = x1
self.x2 = x2
def plus(self):
X3 = self.x1 + self.x2
return X3
How can I make X3 become an attribute which I can access by "self.X3" to use it for other methods I am a newbie, thanks in advance!
Upvotes: 0
Views: 33
Reputation: 19124
For this example, using a property is probably most appropriate. You can read more about the descriptor protocol (for which properties are syntactic sugar) here.
class A:
def __init__ (self, x1, x2):
self.x1 = x1
self.x2 = x2
@property
def X3(self):
return self.x1 + self.x2
Upvotes: 0
Reputation: 467
class A:
def __init__ (self, x1, x2):
self.x1 = x1
self.x2 = x2
def plus(self):
self.X3 = self.x1 + self.x2
return self.X3
if __name__ == '__main__':
a = A(1, 2)
print a.plus()
Give this a try. I got some issues compiling when I tried adding (self) after class A.
Upvotes: 0
Reputation: 69495
simply Change X3 =
to: self.X3=
class A(self):
def __init__ (self, x1, x2):
self.x1 = x1
self.x2 = x2
def plus(self):
self.X3 = self.x1 + self.x2
return self.X3
Upvotes: 1
Reputation: 30250
One way would be to simply make X3
an attribute by prepending self.
. For example:
class A(self):
def __init__ (self, x1, x2):
self.x1 = x1
self.x2 = x2
def plus(self):
self.X3 = self.x1 + self.x2
return self.X3
I'm not sure it's the best approach, but it's hard to tell based on your question.
Upvotes: 2