简体   繁体   中英

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?

class Class:
    _member = 1

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

Class.method()

And:

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

您可以使用self._member ,如果它不是对象的属性(在self.__dict__ ),我相信它会在接下来的__dict__类中查找,该类应包含类属性。

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
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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM