Hi,
Thank you,I have some doubt in python programming like
1)Difference in between module,library,package.
2)what is difference in between built in and keyword.
Eg: None,True is Builtins not keywords.
3)what is the use of writing the code(to call main method)
if __name__=__main__:main
rather than simple mian call main()

4) can i accesee the attributes of class,using class name
like below code

class A:
atri=9
def method(self):
print 'This is method'

def my():

print 'attribute access using Class name ',A.atri
print 'methdo calling using Class name ',A.method()

my()


thanks
Mukthyar

Recommended Answers

All 8 Replies

True is builtin:

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarn
ing', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'Generato
rExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'L
ookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'P
endingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'Syntax
Error', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDeco
deError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs','all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
>>> 'True' in dir(__builtins__)
True

Once again:

A Python package is a reference to the name of the folder containing a number of files. A library is the reference to a specific file, can be a .py file.

For instance in Python2 you use:
import Tkinter
this uses file Tkinter.py somewhere in your Lib folder.
Tkinter.py is a module.
Module names are case sensitive.

In Python3 this has changed to a package and you use:
import tkinter
this uses the files in a subfolder called tkinter in your Lib or Lib/site-packages folder.
Package subfolders have a file __init__.py in them.
Python will look at this file first.
Package names are also case sensitive.
By convention package names are in lower case.

Line if __name__ == '__main__': does not have to be used unless you want to use your program as a module and test it ...

# use if __name__ == '__main__': for testing a module
# allows the program to run or be an importable module
# __main__ is the name-space of the current program
# if a module is imported, the name-space changes to the name of the module

def function1():
    print('hello from function1')

# test the module
# this code block will be ignored if imported as a module
if __name__ == '__main__':
  function1()

Let's say you saved the above code as funk1.py, then you can import it into other programs ...

import funk1

# call the module function with the module name-space
funk1.function1()

Please use code tags with your code to preserve the indentations. Otherwise the code is very difficult to read and not too many folks will help.

[code]
your Python code here

[/code]

Indentations are critical with Python to identify blocks of code. The common way is to use 4 spaces. Do not use tabs, they will screw you up sooner or later, because tabs are set to any number of spaces by individual editors. A mixture of tabs and spaces will make your code wrong.

class A:
    atri=9
    def method(self):
        print 'class A method showing atri', self.atri    

def my():
    print 'attribute access using class name -->', A.atri
    # better ...
    # create an instance of the class
    # (normally you would do that anyway)
    a = A()
    print 'attribute access using class instance name -->', a.atri
    print 'calling class method using class instance name -->', a.method()

my()

Keywords are more basic for the Python code ...

# if you use a Python keyword for a variable name 
# you get an error message, your code will not run

from keyword import kwlist

print "A list of Python's keywords:"
for kw in kwlist:
    print kw
    
''' result for Python27 ...
A list of Python's keywords:
and
as
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
with
yield

'''

Just a rehash of Tony's example ...

# print all built-in functions/methods and constants
# avoid using any of those names for your variables, 
# code may run, but you will get nasty run time conflicts

# print out all built-in Python 'functions' in sorted order ...
print '\n'.join(sorted(dir(__builtins__), key=str.lower))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.