Python Tutorial - Tips

if __name__=="_main_"

λͺ¨λ“ˆμ΄ 직접 μ‹€ν–‰λ˜μ—ˆλŠ”μ§€ ν˜Ήμ€ import λ˜μ—ˆλŠ”μ§€ μ•„λ‹Œμ§€ νŒλ‹¨ν•  λ•Œ __name__ λ³€μˆ˜μ˜ 값을 μ‚¬μš©ν•©λ‹ˆλ‹€.

일반적으둜, λͺ¨λ“ˆμ€ 직접 μ‹€ν–‰λ˜κ±°λ‚˜ λ‹€λ₯Έ λͺ¨λ“ˆμ—μ„œ import λ˜μ–΄ μ‚¬μš©λ©λ‹ˆλ‹€. λ§Œμ•½ λͺ¨λ“ˆμ΄ 직접 μ‹€ν–‰λ˜λ©΄, __name__ λ³€μˆ˜λŠ” λ¬Έμžμ—΄"__main__"이 ν• λ‹Ήλ©λ‹ˆλ‹€. λ°˜λŒ€λ‘œ, λͺ¨λ“ˆμ΄ import λ˜μ–΄ μ‚¬μš©λ  λ•ŒλŠ”,__name__λ³€μˆ˜λŠ” ν•΄λ‹Ή λͺ¨λ“ˆμ˜ 이름(파일λͺ…)이 ν• λ‹Ήλ©λ‹ˆλ‹€.

λ”°λΌμ„œ, __name__ λ³€μˆ˜μ˜ 값을"__main__"κ³Ό λΉ„κ΅ν•˜λ©΄ ν˜„μž¬ λͺ¨λ“ˆμ΄ 직접 μ‹€ν–‰λ˜λŠ”μ§€(import λ˜λŠ”μ§€)λ₯Ό νŒλ‹¨ν•  수 μžˆμŠ΅λ‹ˆλ‹€. λ”°λΌμ„œ μ½”λ“œλ₯Ό ifname == "main"λ‘œκ°μ‹Έλ©΄, ν•΄λ‹Ή 파일이 λͺ¨λ“ˆλ‘œ μ‚¬μš©λ  λ•ŒλŠ” μ‹€ν–‰λ˜μ§€ μ•Šκ³ , 직접 싀행될 λ•Œλ§Œ μ‹€ν–‰λ©λ‹ˆλ‹€.

μž₯점:

  • λͺ¨λ“ˆλ‘œ μ‚¬μš©λ  λ•ŒλŠ” μ½”λ“œκ°€ μ‹€ν–‰λ˜μ§€ μ•ŠμœΌλ―€λ‘œ, λ‹€λ₯Έ λͺ¨λ“ˆμ—μ„œ ν•΄λ‹Ή λͺ¨λ“ˆμ„ import ν•  λ•Œ λ°œμƒν•  수 μžˆλŠ” λΆ€μž‘μš©μ„ λ°©μ§€ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

  • λͺ¨λ“ˆμ„ κ°œλ°œν•  λ•Œ, ν…ŒμŠ€νŠΈ μ½”λ“œλ₯Ό μΆ”κ°€ν•˜κ³  싢을 λ•Œ,if name == "main":ꡬ문을 ν™œμš©ν•˜μ—¬, ν•΄λ‹Ή λͺ¨λ“ˆμ„ 직접 μ‹€ν–‰ν•  λ•Œλ§Œ ν…ŒμŠ€νŠΈ μ½”λ“œκ°€ μ‹€ν–‰λ˜λ„λ‘ ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

# calc.py
def add(a, b):
    return a + b 
def mul(a, b):
    return a * b

print('calc.py __name__:', __name__)    # __name__ λ³€μˆ˜ 좜λ ₯ 
if __name__ == '__main__':    # ν”„λ‘œκ·Έλž¨μ˜ μ‹œμž‘μ μΌ λ•Œλ§Œ μ•„λž˜ μ½”λ“œ μ‹€ν–‰
    print(add(10, 20))
    print(mul(10, 20))
    



# cal_main.py
import calc
print('calc_main.py __name__:', __name__)    # __name__ λ³€μˆ˜ 좜λ ₯
calc.add(50, 60)
## calc.py μ‹€ν–‰μ‹œ
# μ‹€ν–‰κ²°κ³Ό
calc.py __name__: calc
30
200


## calc_main.py μ‹€ν–‰μ‹œ
calc_main.py __name__: calc_main
110   # >>> calc.add(50, 60)

Class in Python

Instance methods

  • Called using objects

  • Must have self as the first parameter

  • (self is another python term. We can use self to access any data or other instance methods which resides in that class. These cannot be accessed without using self)

Initializer Method

  • must be called __init__()~~(~~double underscore is used by python runtime)

  • The first parameter is self

  • If the initializer method is present, the constructor calls __init__()

Super() to inherit all the methods and properties from another class:

  • Inherits all the method, properties of Parent or sibling class

class Child(Parent):
  def __init__(self, txt):
    super().__init__(txt)  # inherit Parent;s method/properties

> **_The underscore prefix in a variable/method name is meant as a _hint to another programmer that a variable or method starting with a single underscore is intended only for internal use. This convention is defined in PEP 8.

# Base class
class House:
    '''
    A place which provides with shelter or accommodation
    '''
    def __init__(self, rooms, bathrooms):
        self.rooms = rooms
        self.bathrooms = bathrooms
    def room_details(self):
        print(f'This property has {self.rooms} rooms \
              with {self.bathrooms} bathrooms')
class Apartment(House):
    '''
    A house within a large building where others also have
    their own house
    '''
    def __init__(self, rooms, bathrooms, floor):
        House.__init__(self, rooms, bathrooms)
        self.floor = floor

# Create an Apartment
apartment = Apartment(2, 2, 21)
apartment.room_details()

Output:
This property has 2 rooms with 2 bathrooms

NP Array

Reshaping arrays

.shape

input_tensor.shape[-1] # get value of the last index of shape

source: read here

source click here

Stacking 2D data to 3D data

 # change to  [rows][cols][channels] for Keras

    # Method0
    x_train3D=np.stack((x_train,x_train,x_train),axis=2) 

    # Method1
    # numpy(channel,r,c) [channels].[rows][cols]
    x_train3D=np.stack((x_train,x_train,x_train))  
    print(x_train3D.shape)    
    x_train3D=np.moveaxis(x_train3D,0,2)
    print(x_train3D.shape)

    x_test3D=np.stack((x_test,x_test,x_test))
    x_test3D=np.moveaxis(x_test3D,0,2)
    print(x_test3D.shape)


    # NEEDS TO BE MODIFIED  (stack-->concatenate)
    # Method2
    x_train=np.expand_dims(x_train,axis=2)
    print(x_train.shape)
    x_train3D=np.stack((x_train,x_train,x_train),axis=1)  
    print(x_train3D.shape)

    # Method3
    x_train=np.reshape(x_train,[x_train.shape[0],x_train.shape[1],1])
    print(x_train.shape)
    x_train3D=np.stack((x_train,x_train,x_train))  
    print(x_train3D.shape)

Documenting your code in Python (docstring)

An official specification on how you should format your docstrings called PEP 0257, based on reStructuredText (reST)

For Google style guide for C++, read here

Google format

"""
Google Style

Args:
    param1: This is the first param.
    param2: This is a second param.

Returns:
    This is a description of what is returned.

Raises:
    KeyError: Raises an exception.
"""
  • Names to Avoid

    • dashes (-) in any package/module name

    • Use CapWords for class names, but lower_with_under.py for module names.

  • Guidelines for naming

  • Type
    Public
    Internal

    Packages

    lower_with_under

    Modules

    lower_with_under

    _lower_with_under

    Classes

    CapWords

    _CapWords

    Exceptions

    CapWords

    Functions

    lower_with_under()

    _lower_with_under()

    Global/Class Constants

    CAPS_WITH_UNDER

    _CAPS_WITH_UNDER

    Global/Class Variables

    lower_with_under

    _lower_with_under

    Instance Variables

    lower_with_under

    _lower_with_under (protected)

    Method Names

    lower_with_under()

    _lower_with_under() (protected)

    Function/Method Parameters

    lower_with_under

    Local Variables

    lower_with_under

  • Example Google style docstrings

This module demonstrates documentation as specified by the Google Python Style Guide

"""A one line summary of the module or program, terminated by a period.

Leave one blank line.  The rest of this docstring should contain an
overall description of the module or program.  Optionally, it may also
contain a brief description of exported classes and functions and/or usage
examples

Example:
    Examples can be given using either the ``Example`` or ``Examples``
    sections. Sections support any reStructuredText formatting, including
    literal blocks::

        $ python example_google.py

Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.

Attributes:
    module_level_variable1 (int): Module level variables may be documented in
        either the ``Attributes`` section of the module docstring, or in an
        inline docstring immediately following the variable.

        Either form is acceptable, but the two should not be mixed. Choose
        one convention to document module level variables and be consistent
        with it.

Todo:
    * For module TODOs
    * You have to also use ``sphinx.ext.todo`` extension

.. _Google Python Style Guide:
   https://google.github.io/styleguide/pyguide.html

"""

def function_with_types_in_docstring(param1, param2):
    """Example function with types documented in the docstring.

    `PEP 484`_ type annotations are supported. If attribute, parameter, and
    return types are annotated according to `PEP 484`_, they do not need to be
    included in the docstring:

    Args:
        param1 (int): The first parameter.
        param2 (str): The second parameter.

    Returns:
        bool: The return value. True for success, False otherwise.

    .. _PEP 484:
        https://www.python.org/dev/peps/pep-0484/

    """



def module_level_function(param1, param2=None, *args, **kwargs):
    """This is an example of a module level function.

    Function parameters should be documented in the ``Args`` section. The name
    of each parameter is required. The type and description of each parameter
    is optional, but should be included if not obvious.

    If ``*args`` or ``**kwargs`` are accepted,
    they should be listed as ``*args`` and ``**kwargs``.

    The format for a parameter is::

        name (type): description
            The description may span multiple lines. Following
            lines should be indented. The "(type)" is optional.

            Multiple paragraphs are supported in parameter
            descriptions.

    Args:
        param1 (int): The first parameter.
        param2 (:obj:`str`, optional): The second parameter. Defaults to None.
            Second line of description should be indented.
        *args: Variable length argument list.
        **kwargs: Arbitrary keyword arguments.

    Returns:
        bool: True if successful, False otherwise.
        The ``Returns`` section supports any reStructuredText formatting,
        including literal blocks::

            {
                'param1': param1,
                'param2': param2
            }

    Raises:
        AttributeError: The ``Raises`` section is a list of all exceptions
            that are relevant to the interface.
        ValueError: If `param2` is equal to `param1`.

    """
    if param1 == param2:
        raise ValueError('param1 may not be equal to param2')
    return True

Last updated

Was this helpful?