1 / 3

Understanding Method Syntax and Namespace Management in Python Programming

This resource discusses the concept of method syntax and namespace management in Python, emphasizing how to avoid polluting the global namespace with too many names. It explains the differences between ordinary function calls and method calls, providing examples relevant to programming contexts, such as bodybuilding and list management. The importance of using distinct namespaces for functions to prevent conflicts is highlighted, along with practical examples of method and function invocations, showcasing the significance of structure in clear programming.

tyrell
Download Presentation

Understanding Method Syntax and Namespace Management in Python Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Method syntax Michael Ernst CSE 190p University of Washington

  2. Digression: two meanings of period (.) • Namespace management: math.sin(math.pi) • Purpose: avoid polluting the global environment (the oldest “stack frame”) with too many names • Example: • abs is in the global namespace • When writing a program about bodybuilding, you might use abs (for abdominals) • Suddenly, all code that depends on the built-in abs fails! • Anther examples: draw() function for pictures, for cowboys, and for curtains • Solution: A different namespace or module • “Method syntax” for a function call: mylist.append(new_elt) • append() takes two arguments • First argument may appear before a period • These are distinct meanings of a single token, “.”

  3. Method call syntax • Ordinary function call: fn(arg1, arg2, arg3) • Any Python function can be invoked this way • “Method syntax”: arg1.fn(arg2, arg3) • First argument may appear before a period • Some Python functions can be invoked this way • Only works for functions defined in a type’s namespace • Such a function is called a “method” nums = [1, 2, 3] nums.append(4) list.append(nums, 5) # append is defined in the list namespace append(nums, 6) # NameError: name 'append' is not defined len(nums) nums.len() # AttributeError: 'list' object has no attribute 'len‘

More Related