Reputation: 1553
class Class:
_member = 1
def method(self):
I want to access _member
from within method()
, what is the correct way to do so?
Upvotes: 0
Views: 1252
Reputation:
class Class:
_member = 1
def method(self):
print(Class._member)
Class().method()
Would give the output:
1
That one is a Class attribute, by the way. You could call the method as a bound method. You have the option of staticmethod (no first parameter required), classmethod (first one parameter is a class) and normal method (like this one).
Upvotes: 0
Reputation: 5061
class Class:
_member = 1
@classmethod
def method(cls):
print cls._member
Class.method()
And:
>>> Class().method()
1
>>>
Upvotes: 2
Reputation: 26667
class Class:
_member = 1
def method(self):
print "value is ",self._member
create an instance of the class and call the method
c = Class()
c.method()
output:
value is 1
Upvotes: 0
Reputation: 6730
You can use self._member
, if it isn't an attribute of the object (in self.__dict__
) I believe it looks in the classes __dict__
next, which should contain the class attributes.
Upvotes: 1