파이썬의 목적 __repr__
def __repr__(self):
return '<%s %s (%s:%s) %s>' % (
self.__class__.__name__, self.urlconf_name, self.app_name,
self.namespace, self.regex.pattern)
이 방법의 의미 / 목적은 무엇입니까?
__repr__
이 객체를 생성 할 수있는 방법 중 하나 인 객체의 인쇄 가능한 표현을 반환해야 합니다. 공식 문서를 참조 하십시오 . 최종 사용자를위한 __repr__
반면 개발자를 __str__
위한 것입니다.
간단한 예 :
>>> class Point:
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __repr__(self):
... return 'Point(x=%s, y=%s)' % (self.x, self.y)
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)
repr ( object ) : 인쇄 가능한 객체 표현이 포함 된 문자열을 반환합니다. 이것은 변환에 의해 산출 된 값과 같습니다 (역 따옴표). 이 기능을 일반 기능으로 액세스 할 수있는 경우가 종종 있습니다. 많은 유형의 경우이 함수는에 전달 될 때 동일한 값을 가진 객체를 생성하는 문자열을 반환하려고 시도합니다
eval()
. 그렇지 않으면 표현은 추가 정보와 함께 객체 유형의 이름을 포함하는 꺾쇠 괄호로 묶인 문자열입니다. 종종 개체의 이름과 주소를 포함합니다. 클래스는__repr__()
메소드 를 정의하여이 함수가 인스턴스에 대해 리턴하는 것을 제어 할 수 있습니다 .
여기서 보시는 것은의 기본 구현으로 __repr__
, 직렬화 및 디버깅에 유용합니다.
__repr__
독립형 Python 인터프리터에서 클래스를 인쇄 가능한 형식으로 표시하는 데 사용됩니다. 예:
~> python3.5
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class StackOverflowDemo:
... def __init__(self):
... pass
... def __repr__(self):
... return '<StackOverflow demo object __repr__>'
...
>>> demo = StackOverflowDemo()
>>> demo
<StackOverflow demo object __repr__>
__str__
메소드가 클래스에 정의되지 않은 경우 __repr__
인쇄 가능한 표현을 작성하기 위해 함수를 호출합니다 .
>>> str(demo)
'<StackOverflow demo object __repr__>'
또한 print()
클래스를 호출하면 __str__
기본적으로 호출 됩니다.
__repr__의 방법은 단순히 클래스의 객체를 인쇄하는 방법을 파이썬을 알려줍니다
그들 사이의 차이점을 보는 예 ( 이 출처 에서 복사했습니다 ),
>>> x=4
>>> repr(x)
'4'
>>> str(x)
'4'
>>> y='stringy'
>>> repr(y)
"'stringy'"
>>> str(y)
'stringy'
The returns of repr()
and str()
are identical for int x
, but there's a difference between the return values for str
y
-- one is formal and the other is informal. One of the most important differences between the formal and informal representations is that the default implementation of __repr__
for a str value can be called as an argument to eval, and the return value would be a valid string object, like this:
>>> repr(y)
"'a string'"
>>> y2=eval(repr(y))
>>> y==y2
True
If you try to call the return value of __str__
as an argument to eval, the result won't be valid.
When we create new types by defining classes, we can take advantage of certain features of Python to make the new classes convenient to use. One of these features is "special methods", also referred to as "magic methods".
Special methods have names that begin and end with two underscores. We define them, but do not usually call them directly by name. Instead, they execute automatically under under specific circumstances.
It is convenient to be able to output the value of an instance of an object by using a print statement. When we do this, we would like the value to be represented in the output in some understandable unambiguous format. The repr special method can be used to arrange for this to happen. If we define this method, it can get called automatically when we print the value of an instance of a class for which we defined this method. It should be mentioned, though, that there is also a str special method, used for a similar, but not identical purpose, that may get precedence, if we have also defined it.
If we have not defined, the repr method for the Point3D class, and have instantiated my_point as an instance of Point3D, and then we do this ...
print my_point ... we may see this as the output ...
Not very nice, eh?
So, we define the repr or str special method, or both, to get better output.
**class Point3D(object):
def __init__(self,a,b,c):
self.x = a
self.y = b
self.z = c
def __repr__(self):
return "Point3D(%d, %d, %d)" % (self.x, self.y, self.z)
def __str__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1, 2, 3)
print my_point # __repr__ gets called automatically
print my_point # __str__ gets called automatically**
Output ...
(1, 2, 3) (1, 2, 3)
Implement repr for every class you implement. There should be no excuse. Implement str for classes which you think readability is more important of non-ambiguity.
Refer this link: https://www.pythoncentral.io/what-is-the-difference-between-str-and-repr-in-python/
참고URL : https://stackoverflow.com/questions/1984162/purpose-of-pythons-repr
'Programing' 카테고리의 다른 글
C #에서 ToUpper ()와 ToUpperInvariant ()의 차이점은 무엇입니까? (0) | 2020.07.14 |
---|---|
PostgreSQL DB에서 현재 연결 수를 가져 오는 올바른 쿼리 (0) | 2020.07.14 |
인터페이스를 구현하는 추상 클래스가 왜 인터페이스 메소드 중 하나의 선언 / 구현을 놓칠 수 있습니까? (0) | 2020.07.14 |
R에서 키 누르기를 기다리는 방법? (0) | 2020.07.14 |
AngularJs 앱을 작성할 때 Jade 또는 Handlebars를 사용하는 것은 무엇입니까 (0) | 2020.07.14 |