IT박스

루비에서 파이썬 배우기;

itboxs 2020. 7. 2. 08:05
반응형

루비에서 파이썬 배우기; 차이점과 유사점


나는 루비를 잘 알고있다. 나는 현재 파이썬을 배울 필요가 있다고 생각합니다. 두 가지를 모두 알고있는 사람들에게는 두 개념이 비슷한 개념과 다른 개념은 무엇입니까?

JavaScripter를 위해 Learning Lua를 위해 작성한 입문서와 비슷한 목록을 찾고 있습니다 . 공백의 중요성 및 루핑 구문과 같은 간단한 것들; nil파이썬 의 이름 , 그리고 "가상"으로 간주되는 값; 그것은 동등한 사용하는 관용적 인 mapeach, 또는이다 중얼 somethingaboutlistcomprehensions가 중얼 규범?

다양한 답변을 얻을 수 있다면 커뮤니티 위키로 모아서 기쁩니다. 그렇지 않으면 당신은 모두 하나의 진정한 포괄적 인 목록을 만들려고 서로 싸울 수 있습니다.

편집 : 분명히, 내 목표는 "적절하고"관용적 인 파이썬입니다. 파이썬과 동등한 파이썬이 inject있지만 목록을 반복하고 결과를 누적시키는 일반적인 기능을 수행하는 더 나은 / 다른 방법이 있기 때문에 아무도 그것을 사용하지 않는다면, 나는 당신이하는 일을 알고 싶습니다. 아마도이 질문을 일반적인 목표 목록, 루비에서 어떻게 달성하는지, 파이썬에서 동등한 것이 무엇인지 물어볼 것입니다.


다음은 몇 가지 주요 차이점입니다.

  1. 루비에는 블록이 있습니다. 파이썬은 그렇지 않습니다.

  2. 파이썬에는 함수가 있습니다. 루비는 그렇지 않습니다. 파이썬에서는 어떤 함수 나 메소드를 가져 와서 다른 함수로 전달할 수 있습니다. 루비에서는 모든 것이 메소드이므로 메소드를 직접 전달할 수 없습니다. 대신, 당신은 그들을 전달하기 위해 Proc 's에 포장해야합니다.

  3. 루비와 파이썬은 클로저를 지원하지만 다른 방식으로 지원합니다. 파이썬에서는 다른 함수 안에 함수를 정의 할 수 있습니다. 내부 함수는 외부 함수에서 변수에 대한 읽기 액세스 권한을 갖지만 쓰기 액세스는 할 수 없습니다. Ruby에서는 블록을 사용하여 클로저를 정의합니다. 클로저는 외부 범위에서 변수에 대한 전체 읽기 및 쓰기 액세스 권한을 갖습니다.

  4. 파이썬에는 목록 이해력이 있습니다. 예를 들어 숫자 목록이 있으면 다음과 같이 쓸 수 있습니다.

    [x*x for x in values if x > 15]
    

    15보다 큰 모든 값의 제곱의 새로운 목록을 얻으려면 Ruby에서 다음을 작성해야합니다.

    values.select {|v| v > 15}.map {|v| v * v}
    

    루비 코드는 컴팩트하지 않습니다. 또한 값 배열을 먼저 15보다 큰 값을 포함하는 더 짧은 중간 배열로 변환하기 때문에 효율적이지 않습니다. 그런 다음 중간 배열을 가져와 중간 사각형을 포함하는 최종 배열을 생성합니다. 그런 다음 중간 배열이 처리됩니다. 따라서 Ruby는 계산 중에 메모리에 3 개의 배열로 끝납니다. 파이썬은 입력 목록과 결과 목록 만 필요합니다.

    파이썬도 비슷한지도 이해력을 제공합니다.

  5. 파이썬은 튜플을 지원합니다; 루비는 그렇지 않습니다. Ruby에서는 배열을 사용하여 튜플을 시뮬레이션해야합니다.

  6. Ruby는 switch / case 문을 지원합니다. 파이썬은 그렇지 않습니다.

  7. 루비는 표준 expr ? val1 : val2삼항 연산자를 지원합니다 . 파이썬은 그렇지 않습니다.

  8. 루비는 단일 상속 만 지원합니다. 다중 상속을 모방해야하는 경우 모듈을 정의하고 믹스 인을 사용하여 모듈 메소드를 클래스로 가져올 수 있습니다. 파이썬은 모듈 믹스 인보다는 다중 상속을 지원합니다.

  9. 파이썬은 단선 람다 함수 만 지원합니다. 일종의 람다 함수 인 루비 블록은 임의로 커질 수 있습니다. 이 때문에 Ruby 코드는 일반적으로 Python 코드보다 더 기능적인 스타일로 작성됩니다. 예를 들어, Ruby에서 목록을 반복하려면 일반적으로

    collection.each do |value|
      ...
    end
    

    블록은에 전달되는 함수와 매우 유사합니다 collection.each. 파이썬에서 동일한 작업을 수행하려면 명명 된 내부 함수를 정의한 다음 각 메소드에 컬렉션에 전달해야합니다 (목록 이이 메소드를 지원하는 경우).

    def some_operation(value):
      ...
    
    collection.each(some_operation)
    

    그것은 아주 잘 흐르지 않습니다. 따라서 일반적으로 다음과 같은 비 기능적 접근 방식이 Python에서 사용됩니다.

    for value in collection:
      ...
    
  10. 안전한 방법으로 자원을 사용하는 것은 두 언어 사이에서 상당히 다릅니다. 여기서 문제는 일부 리소스를 할당하고 (파일 열기, 데이터베이스 커서 얻기 등) 임의의 작업을 수행 한 다음 예외가 발생하더라도 안전한 방식으로 닫으려고한다는 것입니다.

    Ruby에서는 블록을 사용하기가 쉽기 때문에 (# 9 참조) 일반적으로이 패턴을 임의의 작업이 리소스에서 수행되도록 블록을 취하는 메소드로 코딩합니다.

    파이썬에서, 임의의 액션을위한 함수를 전달하는 것은 명명 된 내부 함수를 작성해야하기 때문에 조금 복잡합니다 (# 9 참조). 대신 파이썬은 with안전한 리소스 처리를 위해 명령문을 사용합니다 . Python 객체를 올바르게 정리하는 방법을 참조하십시오 . 상세 사항은.


나는 6 년의 루비 후에 파이썬을 배우는데 몇 달을 보냈습니다. 두 언어에 대한 비교는 그리 많지 않았으므로 직접 작성하고 직접 작성하기로 결정했습니다. 지금, 그것은이 되어 주로 함수형 프로그래밍에 관심을하지만 루비의 언급 이후 inject방법을, 나는 우리가 같은 파장에있어 같은데요.

이것이 도움이되기를 바랍니다 : 파이썬의 '추악함'

올바른 방향으로 움직일 수있는 몇 가지 사항 :

  • All the functional programming goodness you use in Ruby is in Python, and it's even easier. For example, you can map over functions exactly as you'd expect:

    def f(x):
        return x + 1
    
    map(f, [1, 2, 3]) # => [2, 3, 4]
    
  • Python doesn't have a method that acts like each. Since you only use each for side effects, the equivalent in Python is the for loop:

    for n in [1, 2, 3]:
        print n
    
  • List comprehensions are great when a) you have to deal with functions and object collections together and b) when you need to iterate using multiple indexes. For example, to find all the palindromes in a string (assuming you have a function p() that returns true for palindromes), all you need is a single list comprehension:

    s = 'string-with-palindromes-like-abbalabba'
    l = len(s)
    [s[x:y] for x in range(l) for y in range(x,l+1) if p(s[x:y])]
    

My suggestion: Don't try to learn the differences. Learn how to approach the problem in Python. Just like there's a Ruby approach to each problem (that works very well givin the limitations and strengths of the language), there's a Python approach to the problem. they are both different. To get the best out of each language, you really should learn the language itself, and not just the "translation" from one to the other.

Now, with that said, the difference will help you adapt faster and make 1 off modifications to a Python program. And that's fine for a start to get writing. But try to learn from other projects the why behind the architecture and design decisions rather than the how behind the semantics of the language...


I know little Ruby, but here are a few bullet points about the things you mentioned:

  • nil, the value indicating lack of a value, would be None (note that you check for it like x is None or x is not None, not with == - or by coercion to boolean, see next point).
  • None, zero-esque numbers (0, 0.0, 0j (complex number)) and empty collections ([], {}, set(), the empty string "", etc.) are considered falsy, everything else is considered truthy.
  • For side effects, (for-)loop explicitly. For generating a new bunch of stuff without side-effects, use list comprehensions (or their relatives - generator expressions for lazy one-time iterators, dict/set comprehensions for the said collections).

Concerning looping: You have for, which operates on an iterable(! no counting), and while, which does what you would expect. The fromer is far more powerful, thanks to the extensive support for iterators. Not only nearly everything that can be an iterator instead of a list is an iterator (at least in Python 3 - in Python 2, you have both and the default is a list, sadly). The are numerous tools for working with iterators - zip iterates any number of iterables in parallel, enumerate gives you (index, item) (on any iterable, not just on lists), even slicing abritary (possibly large or infinite) iterables! I found that these make many many looping tasks much simpler. Needless to say, they integrate just fine with list comprehensions, generator expressions, etc.


In Ruby, instance variables and methods are completely unrelated, except when you explicitly relate them with attr_accessor or something like that.

In Python, methods are just a special class of attribute: one that is executable.

So for example:

>>> class foo:
...     x = 5
...     def y(): pass
... 
>>> f = foo()
>>> type(f.x)
<type 'int'>
>>> type(f.y)
<type 'instancemethod'>

That difference has a lot of implications, like for example that referring to f.x refers to the method object, rather than calling it. Also, as you can see, f.x is public by default, whereas in Ruby, instance variables are private by default.

참고URL : https://stackoverflow.com/questions/4769004/learning-python-from-ruby-differences-and-similarities

반응형