IT story

None 값은 무엇입니까?

hot-time 2020. 7. 24. 07:31
반응형

None 값은 무엇입니까?


나는 파이썬을 공부하고 있으며 그 None가치 를 설명하는 장을 읽었 지만 불행히도이 책은 어느 시점에서 명확하지 않습니다. 내 질문에 대한 답변을 공유하면 내 질문에 대한 답을 찾을 것이라고 생각했습니다.

None가치 무엇이며 어떤 용도로 사용하고 싶습니까?

또한, 나는이 부분의 책을 얻지 못했습니다 :

None변수에 값을 할당하면 변수를 원래의 빈 상태로 재설정 할 수 있습니다.

그게 무슨 뜻이야?

컴퓨터 세계에 대한 지식이 부족하여 대부분의 답변을 이해하지 못했지만 답변은 훌륭했습니다 (클래스, 객체 등에 대해 배우지 못했습니다). 이 문장은 무엇을 의미합니까?

None변수에 값을 할당하면 변수를 원래의 빈 상태로 재설정 할 수 있습니다.

결정적인:

마지막으로 다른 답변을 보면서 답변을 얻었습니다. 시간을내어 도와 주신 모든 분들 (특히 Martijn Pieters와 DSM)에게 감사 드리며, 모든 답변을 최고로 선택할 수 있기를 바라지 만 선택은 1 명으로 제한됩니다. 모든 답변이 훌륭했습니다.


Martijn의 답변 None은 파이썬의 내용을 설명 하고 책이 잘못되었다고 올바르게 말합니다. 파이썬 프로그래머는 원칙적으로 말하지 않을 것이기 때문에

None변수에 값을 할당하면 변수를 원래의 빈 상태로 재설정 할 수 있습니다.

Briggs가 의미하는 바를 이해하는 방법을 설명하기가 어렵고 왜 여기에 아무도 만족하지 않는지 설명 할 수 없습니다. 도움이 될 수있는 하나의 유추 :

파이썬에서 변수 이름은 객체에 붙인 스티커와 같습니다. 모든 스티커에는 고유 한 이름이 적혀 있으며 한 번에 하나의 개체에만있을 수 있지만 원하는 경우 같은 개체에 둘 이상의 스티커를 넣을 수 있습니다. 당신이 쓸 때

F = "fork"

스티커 "F"를 문자열 객체에 넣습니다 "fork". 당신이 쓴다면

F = None

스티커를 None개체 로 옮깁니다 .

무엇 브릭스 상상하도록 요구되는 것은 당신이하지 않은 것입니다 쓰기 스티커를 "F", 거기 에 이미F 온 스티커 None, 그리고 당신이 한 모든이었다 이동 에서, 그것을 None"fork". 따라서 입력 할 때 F = None, None의미 로 취급하기로 결정한 경우 "빈 상태로 원래 상태로 재설정" 됩니다 empty state.

그가 무엇을 얻고 있는지 알 수 있지만, 그것을 보는 것은 나쁜 방법입니다. Python을 시작하고을 입력 print(F)하면

>>> print(F)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'F' is not defined

것을 NameError의미 파이썬은 이름을 인식하지 못하는 F, 그런 스티커가 없기 때문에 . 브릭스가 옳고 원래 상태로 F = None재설정 F되면, 그곳에 있어야합니다.

>>> print(F)
None

같은 우리는 우리가 입력 할 후 F = None와에 스티커를 넣어 None.


이것이 전부입니다. 실제로 파이썬에는 객체 (내장 이름)에 이미 붙어있는 스티커가 붙어 있지만, 다른 스티커는 F = "fork"and A = 2and와 같은 줄로 자신을 작성해야하며 c17 = 3.14나중에 다른 객체에 붙일 수 있습니다 ( F = 10또는 같은 F = None;; 모두 동일합니다) .)

브릭스는 당신이 쓰려고하는 모든 가능한 스티커가 이미 그 None물체에 붙어있는 것처럼 가장하고 있습니다 .


None'빈'또는 '여기에 값이 없음'을 나타내는 데 일반적으로 사용되는 값입니다. 그것은 인 신호 객체 ; 파이썬 문서에는 그 의미가 있다고 말했기 때문에 의미가 있습니다.

주어진 파이썬 인터프리터 세션에는 해당 객체의 사본이 하나만 있습니다.

함수를 작성하고 해당 함수가 명시적인 return명령문을 사용하지 않는 경우 None대신 예를 들어 반환됩니다. 그렇게하면 함수를 사용한 프로그래밍이 훨씬 간단 해집니다. 함수 는 하나의 객체 일지라도 항상 무언가를 반환 None합니다.

명시 적으로 테스트 할 수 있습니다.

if foo is None:
    # foo is set to None

if bar is not None:
    # bar is set to something *other* than None

또 다른 용도는 기능에 '빈'기본값 인 선택적 매개 변수를 제공하는 것입니다.

def spam(foo=None):
    if foo is not None:
        # foo was specified, do something clever!

이 함수 spam()에는 선택적 인수가 있습니다. spam()지정하지 않고 호출 하면 기본값 None이 주어 지므로 함수가 인수와 함께 호출되었는지 여부를 쉽게 감지 할 수 있습니다.

다른 언어들도 비슷한 개념을 가지고 있습니다. SQL은 NULL; JavaScript에는 undefined null 등이 있습니다.

파이썬에서는 변수가 사용되기 때문에 존재합니다. 변수를 먼저 선언 할 필요가 없으므로 파이썬 에는 실제로 변수 가 없습니다 . 변수를 None로 설정하는 것은 기본 빈 값으로 설정하는 것과 다릅니다. 비어 있음 None나타내는 데 자주 사용되지만 값이기도 합니다. 당신이 읽고있는 책이 그 시점에서 오도되고 있습니다.


이것은 파이썬 문서 가 말한 것입니다 None.

types.NoneType의 유일한 값입니다. 기본 인수가 함수에 전달되지 않을 때와 같이 없음은 값이 없음을 나타내는 데 자주 사용됩니다.

버전 2.4에서 변경 : 없음으로 할당은 유효하지 않으며 SyntaxError를 발생시킵니다.

참고 None과 디버그 라는 이름은 속성 이름으로도 할당 할 수 없으므로 SyntaxError가 발생할 수 있으므로“참”상수로 간주 될 수 있습니다.

  1. None먼저 유형을 확인합시다

    print type(None)
    print None.__class__
    

    산출

    <type 'NoneType'>
    <type 'NoneType'>
    

기본적으로, NoneType단지 같은 데이터 타입 int, float등 당신은 파이썬에서 사용할 수있는 기본 유형의 목록을 확인할 수 있습니다 8.15. types — 내장 유형의 이름 .

  1. 그리고 클래스 None의 인스턴스입니다 NoneType. 그래서 우리는 우리 None자신의 인스턴스를 만들고 싶을 것입니다. 한번 해보자

    print types.IntType()
    print types.NoneType()
    

    산출

    0
    TypeError: cannot create 'NoneType' instances
    

따라서 NoneType인스턴스를 만들 수 없습니다 . 우리는 가치의 독창성에 대해 걱정할 필요가 없습니다 None.

  1. None내부적으로 어떻게 구현했는지 확인합시다 .

    print dir(None)
    

    산출

    ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', 
     '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__',
     '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
    

를 제외한 __setattr__나머지는 모두 읽기 전용 속성입니다. 따라서의 속성을 변경할 수있는 방법이 없습니다 None.

  1. 시도하고 새로운 속성을 추가하자 None

    setattr(types.NoneType, 'somefield', 'somevalue')
    setattr(None, 'somefield', 'somevalue')
    None.somefield = 'somevalue'
    

    산출

    TypeError: can't set attributes of built-in/extension type 'NoneType'
    AttributeError: 'NoneType' object has no attribute 'somefield'
    AttributeError: 'NoneType' object has no attribute 'somefield'
    

위의 문은 각각 이러한 오류 메시지를 생성합니다. 즉, None인스턴스 에서 속성을 동적으로 만들 수 없습니다 .

  1. 무언가를 할당 할 때 어떤 일이 발생하는지 확인합시다 None. 설명서에 따라 SyntaxError. 에 무언가를 할당 None하면 프로그램이 전혀 실행되지 않습니다.

    None = 1
    

    산출

    SyntaxError: cannot assign to None
    

우리는 그것을 설립했다

  1. None 의 예입니다 NoneType
  2. None 새로운 속성을 가질 수 없습니다
  3. 의 기존 속성은 None변경할 수 없습니다.
  4. 우리는 다른 인스턴스를 만들 수 없습니다 NoneType
  5. None값을 지정 하여 참조를 변경할 수도 없습니다 .

So, as mentioned in the documentation, None can really be considered as a true constant.

Happy knowing None :)


The book you refer to is clearly trying to greatly simplify the meaning of None. Python variables don't have an initial, empty state – Python variables are bound (only) when they're defined. You can't create a Python variable without giving it a value.

>>> print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> def test(x):
...   print(x)
... 
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 1 argument (0 given)
>>> def test():
...   print(x)
... 
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in test
NameError: global name 'x' is not defined

but sometimes you want to make a function mean different things depending on whether a variable is defined or not. You can create an argument with a default value of None:

>>> def test(x=None):
...   if x is None:
...     print('no x here')
...   else:
...     print(x)
... 
>>> test()
no x here
>>> test('x!')
x!

The fact that this value is the special None value is not terribly important in this case. I could've used any default value:

>>> def test(x=-1):
...   if x == -1:
...     print('no x here')
...   else:
...     print(x)
... 
>>> test()
no x here
>>> test('x!')
x!

…but having None around gives us two benefits:

  1. We don't have to pick a special value like -1 whose meaning is unclear, and
  2. Our function may actually need to handle -1 as a normal input.
>>> test(-1)
no x here

oops!

So the book is a little misleading mostly in its use of the word reset – assigning None to a name is a signal to a programmer that that value isn't being used or that the function should behave in some default way, but to reset a value to its original, undefined state you must use the del keyword:

>>> x = 3
>>> x
3
>>> del x
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

Other answers have already explained meaning of None beautifully. However, I would still like to throw more light on this using an example.

Example:

def extendList(val, list=[]):
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3

Now try to guess output of above list. Well, the answer is surprisingly as below:

list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']

But Why?

Many will mistakenly expect list1 to be equal to [10] and list3 to be equal to ['a'], thinking that the list argument will be set to its default value of [] each time extendList is called.

However, what actually happens is that the new default list is created only once when the function is defined, and that same list is then used subsequently whenever extendList is invoked without a list argument being specified. This is because expressions in default arguments are calculated when the function is defined, not when it’s called.

list1 and list3 are therefore operating on the same default list, whereas list2 is operating on a separate list that it created (by passing its own empty list as the value for the list parameter).


'None' the savior: (Modify example above to produce desired behavior)

def extendList(val, list=None):
    if list is None:
       list = []
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3

With this revised implementation, the output would be:

list1 = [10]
list2 = [123]
list3 = ['a']

Note - Example credit to toptal.com


None is a singleton object (meaning there is only one None), used in many places in the language and library to represent the absence of some other value.


For example:
if d is a dictionary, d.get(k) will return d[k] if it exists, but None if d has no key k.

Read this info from a great blog: http://python-history.blogspot.in/


I love code examples (as well as fruit), so let me show you

apple = "apple"
print(apple)
>>> apple
apple = None
print(apple)
>>> None

None means nothing, it has no value.

None evaluates to False.


largest=none
smallest =none 
While True :
          num =raw_input ('enter a number ') 
          if num =="done ": break 
          try :
           inp =int (inp) 
          except:
              Print'Invalid input' 
           if largest is none :
               largest=inp
           elif inp>largest:
                largest =none 
           print 'maximum', largest

          if smallest is none:
               smallest =none
          elif inp<smallest :
               smallest =inp
          print 'minimum', smallest 

print 'maximum, minimum, largest, smallest 

참고URL : https://stackoverflow.com/questions/19473185/what-is-a-none-value

반응형