Program Tip

Python에서 클래스의 멤버 변수에 액세스합니까?

programtip 2020. 11. 14. 11:00
반응형

Python에서 클래스의 멤버 변수에 액세스합니까?


class Example(object):
    def the_example(self):
        itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)

클래스의 변수에 어떻게 액세스합니까? 이 정의를 추가해 보았습니다.

def return_itsProblem(self):
    return itsProblem

그러나 그것은 또한 실패합니다.


대답은 몇 마디로

귀하의 예에서는 itsProblem지역 변수입니다.

self인스턴스 변수를 설정하고 가져 오는 데 사용해야 합니다. __init__방법 에서 설정할 수 있습니다 . 그러면 코드는 다음과 같습니다.

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

그러나 진정한 클래스 변수를 원한다면 클래스 이름을 직접 사용하십시오.

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

그러나이 변수 theExample.itsProblem는으로 자동 설정 Example.itsProblem되지만 전혀 동일한 변수가 아니며 독립적으로 변경할 수 있으므로주의해야합니다.

몇 가지 설명

Python에서는 변수를 동적으로 만들 수 있습니다. 따라서 다음을 수행 할 수 있습니다.

class Example(object):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem 

인쇄물

진실

따라서 이것이 바로 이전 예제에서 수행하는 작업입니다.

실제로 Python에서는 self사용 this하지만 그 이상입니다. self첫 번째 인수는 항상 개체 참조이기 때문에 모든 개체 메서드에 대한 첫 번째 인수입니다. 전화하든 말든 자동으로 진행됩니다 self.

즉, 다음을 수행 할 수 있습니다.

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

또는:

class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

똑같습니다. ANY 객체 메서드의 첫 번째 인수는 현재 객체이며 self규칙으로 만 호출합니다 . 그리고 외부에서하는 것과 같은 방식으로이 객체에 변수를 추가합니다.

이제 클래스 변수에 대해.

당신이 할 때 :

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

먼저 클래스 변수를 설정 한 다음 객체 (인스턴스) 변수에 액세스 합니다 . 이 개체 변수를 설정하지 않았지만 작동합니다. 어떻게 가능합니까?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variables to set default values to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.


You are declaring a local variable, not a class variable. To set an instance variable (attribute), use

class Example(object):
    def the_example(self):
        self.itsProblem = "problem"  # <-- remember the 'self.'

theExample = Example()
theExample.the_example()
print(theExample.itsProblem)

To set a class variable (a.k.a. static member), use

class Example(object):
    def the_example(self):
        Example.itsProblem = "problem"
        # or, type(self).itsProblem = "problem"
        # depending what you want to do when the class is derived.

If you have an instance function (i.e. one that gets passed self) you can use self to get a reference to the class using self.__class__

For example in the code below tornado creates an instance to handle get requests, but we can get hold of the get_handler class and use it to hold a riak client so we do not need to create one for every request.

import tornado.web
import riak

class get_handler(tornado.web.requestHandler):
    riak_client = None

def post(self):
    cls = self.__class__
    if cls.riak_client is None:
        cls.riak_client = riak.RiakClient(pb_port=8087, protocol='pbc')
    # Additional code to send response to the request ...

Implement the return statement like the example below! You should be good. I hope it helps someone..

class Example(object):
    def the_example(self):
        itsProblem = "problem"
        return itsProblem 


theExample = Example()
print theExample.the_example()

참고URL : https://stackoverflow.com/questions/3434581/accessing-a-class-member-variables-in-python

반응형