Quaker
Quaker

Reputation: 1553

How can I access a class data member from a method within the same class?

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

Answers (4)

user3058846
user3058846

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

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

class Class:
    _member = 1

    @classmethod
    def method(cls):
        print cls._member

Class.method()

And:

>>> Class().method()
1
>>> 

Upvotes: 2

nu11p01n73R
nu11p01n73R

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

GP89
GP89

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

Related Questions