Saturday, 21 April 2018

Python - OOPS--getter,setter -- Day 26

  • this explains setter ,getter and decorator
  • https://www.udemy.com/python-the-complete-python-developer-course/learn/v4/t/lecture/6022196?start=0
  •   
    #getter and setter
    #this program explains about the use of get and set methods and property keyword
    #this class will be imported in the getsetmain.py,there is no need of importing this class
    #but for the clarity and navigation purpose written as 2 programs
    
    #set and get nethods can be used to set as well as check certain conditions
    #the return variables and the assignment variable name s/b different ie..level:_lvel and lives:_lives
    #if not it will result in error due to recursive
    
    #few simple objectives like lives cannot be less than 0
    #and score multiplied by 1000 for each level are achieved
    class Player:
        def __init__(self,name):
            self.name = name
            self._lives=3
            self._level = 1
            self._score=0
    
        def _setlife(self,live):
            if live>=0:
                self._lives = live
            else:
                print('live cannot be negative')
                self._lives=0
    
        def _getlife(self):
            return self._lives
    
        def _setlevel(self,level):
            if level>=1:
                delta = level-self._level
                self._score += delta * 1000
                self._level = level
            else:
                print('level cannot be less than 1 ')
    
        def _getlevel(self):
            return self._level
    
        lives = property(_getlife,_setlife)
        level = property(_getlevel,_setlevel)
    
    ####decorator
    #this is similar to the property but with different syntax
    
    #getter
        @property
        def score(self):
            return self._score
    
    #setter
        @score.setter
        def score(self,score):
            self._score = score
    
    
        def __str__(self):
            return("{0.name};lives:{0.lives};level:{0.level};score:{0.score}".format(self))
     
    
  • main program using the above imported class
  •   
    #we can use getsetplayer.Player, but since it is tedious
    #we have used the from and import like below
    
    
    
    
    from getsetplayer import Player
    
    tim = Player('tim')
    # print(tim.name)
    # print(tim.lives)
    # print(tim.score)
    # print(tim.level)
    
    print(tim)
    tim.lives-=1
    print(tim)
    tim.lives-=1
    print(tim)
    tim.lives-=1
    print(tim)
    tim.lives-=1
    print(tim)
    tim.lives=3
    tim.level+=1
    print('*********')
    print(tim)
    tim.level+=1
    print(tim)
    print('*********')
    tim.score = 500
    print(tim)
     
    

    Python - OOPS Basics-avoid circular reference- Day 26(5 days later)

  • there is circular reference in this example ie the song class has the artist object referred in it , similarly album also has artist object reference,we can remove by using their name alone instead of the whole object
  • this program explains how the class ,fields,methods can be used to store the set of info with the same format(like artist,album,song)
  •   
    
    class Song:
        """Class to represent a song
    
        Attributes:
            title (str): The title of the song
            artist (str): An artist name representing the songs creator.
            duration (int): The duration of the song in seconds.  May be zero
        """
    
        def __init__(self, title, artist, duration=0):
            self.name = title
            self.artist = artist
            self.duration = duration
    
    
    class Album:
        """ Class to represent an Album, using it's track list
    
        Attributes:
            name (str): The name of the album.
            year (int): The year was album was released.
            artist: (str): The name of the artist responsible for the album. If not specified,
            the artist will default to an artist with the name "Various Artists".
            tracks (List[Song]):  A list of the songs on the album.
    
        Methods:
            add_song: Used to add a new song to the album's track list.
        """
    
        def __init__(self, name, year, artist=""):
            self.name = name
            self.year = year
            if artist is None:
                self.artist = "Various Artists"
            else:
                self.artist = artist
    
            self.tracks = []
    
        def add_song(self, songname, position=None):
            """Adds a song to the track list
    
            Args:
                song (Song): A song to add.
                position (Optional[int]): If specified, the song will be added to that position
                    in the track list - inserting it between other songs if necessary.
                    Otherwise, the song will be added to the end of the list.
            """
            song_found = find_object(songname,self.tracks)
            if song_found is None:
                song_found = Song(songname,self.artist)
                if position is None:
                    self.tracks.append(song_found)
                else:
                    self.tracks.insert(position, song_found)
    
    class Artist:
        """Basic class to store artist details.
    
        Attributes:
            name (str): The name of the artist.
            albums (List[Album]): A list of the albums by this artist.
                The list includes only those albums in this collection, it is
                not an exhaustive list of the artist's published albums.
    
        Methods:
            add_album: Use to add a new album to the artist's albums list
        """
    
        def __init__(self, name):
            self.name = name
            self.albums = []
    
        def add_album(self, album):
            """Add a new album to the list.
    
            Args:
                album (Album): Album object to add to the list.
                    If the album is already present, it will not added again (although this is yet to implemented).
            """
            self.albums.append(album)
    
        def add_song(self, album_name, year, song_name):
            """Add a new song to the collection of albums
    
            This method will add the song to an album in the collection.
            A new album will be created in the collection if it doesn't already exist.
    
            Args:
                name (str): The name of the album
                year (int): The year the album was produced
                title (str): The title of the song
            """
            album_found = find_object(album_name, self.albums)
            if album_found is None:
                # print(name + " not found")
                album_found = Album(album_name, year, self.name)
                self.add_album(album_found)
            else:
                print("Found album " + album_name)
    
            album_found.add_song(song_name)
    
    
    def find_object(field, object_list):
        """Check 'object_list' to see if an object with a 'name' attribute equal to 'field' exists, return it if so."""
        for item in object_list:
            if item.name == field:
                return item
        return None
    
    
    def load_data():
    
        artist_list = []
    
        with open("albums.txt", "r") as albums:
            for line in albums:
                # data row should consist of (artist, album, year, song)
                artist_field, album_field, year_field, song_field = tuple(line.strip('\n').split('\t'))
                year_field = int(year_field)
                # print("{}:{}:{}:{}".format(artist_field, album_field, year_field, song_field))
    
                new_artist = find_object(artist_field, artist_list)
                if new_artist is None:
                    new_artist = Artist(artist_field)
                    artist_list.append(new_artist)
    
                new_artist.add_song(album_field, year_field, song_field)
    
        return artist_list
    
    
    def create_checkfile(artist_list):
        """Create a check file from the object data for comparison with the original file"""
        with open("checkfile.txt", 'w') as checkfile:
            for new_artist in artist_list:
                for new_album in new_artist.albums:
                    for new_song in new_album.tracks:
                        print("{0.name}\t{1.name}\t{1.year}\t{2.name}".format(new_artist, new_album, new_song),
                              file=checkfile)
    
    
    if __name__ == '__main__':
        artists = load_data()
        print("There are {} artists".format(len(artists)))
    
        create_checkfile(artists)
    
    
     
    

    Python - OOPS Basics-eg2 - artist,album,song - Day 26(5 days later)

  • this program needs a album file which can be downloaded from udemy and place it in the appropriate working folder
  • this program explains how the class ,fields,methods can be used to store the set of info with the same format(like artist,album,song)
  •   
    class Song:
        """Class to represent a song
    
        Attributes:
            title (str): The title of the song
            artist (Artist): An artist object representing the songs creator.
            duration (int): The duration of the song in seconds.  May be zero
        """
    
        def __init__(self, title, artist, duration=0):
            self.title = title
            self.artist = artist
            self.duration = duration
    
    
    class Album:
        """ Class to represent an Album, using it's track list
    
        Attributes:
            name (str): The name of the album.
            year (int): The year was album was released.
            artist: (Artist): The artist responsible for the album. If not specified,
            the artist will default to an artist with the name "Various Artists".
            tracks (List[Song]):  A list of the songs on the album.
    
        Methods:
            add_song: Used to add a new song to the album's track list.
        """
    
        def __init__(self, name, year, artist=None):
            self.name = name
            self.year = year
            if artist is None:
                self.artist = Artist("Various Artists")
            else:
                self.artist = artist
    
            self.tracks = []
    
        def add_song(self, song, position=None):
            """Adds a song to the track list
    
            Args:
                song (Song): A song to add.
                position (Optional[int]): If specified, the song will be added to that position
                    in the track list - inserting it between other songs if necessary.
                    Otherwise, the song will be added to the end of the list.
            """
            if position is None:
                self.tracks.append(song)
            else:
                self.tracks.insert(position, song)
    
    
    class Artist:
        """Basic class to store artist details.
    
        Attributes:
            name (str): The name of the artist.
            albums (List[Album]): A list of the albums by this artist.
                The list includes only those albums in this collection, it is
                not an exhaustive list of the artist's published albums.
    
        Methods:
            add_album: Use to add a new album to the artist's albums list
        """
    
        def __init__(self, name):
            self.name = name
            self.albums = []
    
        def add_album(self, album):
            """Add a new album to the list.
    
            Args:
                album (Album): Album object to add to the list.
                    If the album is already present, it will not added again (although this is yet to implemented).
            """
            self.albums.append(album)
    
    
    
    def load_data():
        new_artist = None
        new_album = None
        artist_list = []
    
        with open("albums.txt", "r") as albums:
            for line in albums:
                # data row should consist of (artist, album, year, song)
    
                artist_field, album_field, year_field, song_field = tuple(line.strip('\n').split('\t'))
                year_field = int(year_field)
                # print("{}:{}:{}:{}".format(artist_field, album_field, year_field, song_field))
    
                if new_artist is None:
                    new_artist = Artist(artist_field)
                elif new_artist.name != artist_field:
                    # We've just read details for a new artist
                    # store the current album in the currents artists collection then create a new artist object
                    new_artist.add_album(new_album)
                    artist_list.append(new_artist)
                    new_artist = Artist(artist_field)
                    new_album = None
    
                if new_album is None:
                    new_album = Album(album_field, year_field, new_artist)
                elif new_album.name != album_field:
                    # We've just read a new album for the current artist
                    # store the current album in the artist's collection then create a new album object
                    new_artist.add_album(new_album)
                    new_album = Album(album_field, year_field, new_artist)
    
                # create a new song object and add it to the current album's collection
                new_song = Song(song_field, new_artist)
                new_album.add_song(new_song)
    
            # After read the last line of the text file, we will have an artist and album that haven't
            #  been store - process them now
            if new_artist is not None:
                if new_album is not None:
                    new_artist.add_album(new_album)
                artist_list.append(new_artist)
    
        return artist_list
        # print(artist_list)
    
    
    def create_checkfile(artist_list):
        """Create a check file from the object data for comparison with the original file"""
        with open("checkfile.txt", 'w') as checkfile:
            for new_artist in artist_list:
                for new_album in new_artist.albums:
                    for new_song in new_album.tracks:
                        print("{0.name}\t{1.name}\t{1.year}\t{2.title}".format(new_artist, new_album, new_song),
                              file=checkfile)
    
    
    if __name__ == '__main__':
        artists = load_data()
        print("There are {} artists".format(len(artists)))
        #
        # create_checkfile(artists)
    
     
    
  • #In the previous program if the sort order of the artsist and album is ascending it will work properly, but if it is changed ,then it will show the wrong count,this is because the artsist object is created based oh the last inserted artist album..ie if the 2 nd inserted object repeats again at the last line then it will be treated as new artist again which is not the case this problem will be solved if look at the object list ,whether the artist or album list is already created or not ,if it created we can simply get the name and make use of,this is explained in the nex example program
  •   
    class Song:
        """
        class to represent a song
    
        Attributes:
            title():The tile of the song
            artist(Artist):An artist object representing the songs creator
            duration (int):The duration of the song in seconds.May be Zero
        """
        def __init__(self,title,artist,duration=0):
            """song init method
            Args:
                title(str):Initialises the 'title' attribute
                artist(Artist):An artist object representing the songs creator
                duration (optional int):initialise value to 'duration' attribute
                        will be defaulted to zero if not specified.
            """
            self.title = title
            self.artist = artist
            self.duration = duration
    
    
    class Album:
        """ class to represent a album,using its track list
    
        Attributes:
            name (str):The name of the album.
            year (int):The year the album was released.
            artist :(Artist):The artist responsible for the album.If not specified,
            the artist will default to an artist with the name "Various Artists".
            tracks (List[Song]):A List of songs on the album
    
            Methods:
                add_song:used to add a new song to the albums track list
        """
    
        def __init__(self,name,year,artist =None):
            self.name = name
            self.year = year
            if artist is None:
                self.artist = Artist("Various artists")
            else:
                self.artist = artist
    
            self.tracks = []
    
        def add_song(self,song,position = None):
            """Adds a song to the track list
    
            Args:
                song(Song):A song to add.
                position (optional[int]):If specified,the song will be added to that position
                    in the track list  - inserting it between other songs if necessary.
                    Otherwise,the song will be added to the end of tthe list
            """
    
            if position is None:
                self.tracks.append(song)
            else:
                self.tracks.insert(position,song)
    
    
    class Artist:
        """Basic class to store artist details
    
        Attributes:
            name(str):The name of the artist
            albums (List[Album]):A list of albums by this artist.
                    The list includes only those albums in this collection,it is
                    not an exhaustive list of the artist's published albums
    
        Methods:
            add_album:used to add a new album to the artists's album list
    
        """
    
        def __init__(self,name):
            self.name = name
            self.albums = []
    
        def add_album(self,album):
            """
            Add a new album to the list.
    
            Args:
                album(Album):Album object to add to the list.
                    If the album is already present,it will not be added again (although it is yet to be implemented).
            """
            self.albums.append(album)
    
    
    def checkobjectexist (field,object_list):
        for item in object_list:
            if item.name == field:
                return item
        return None
    
    def load_data():
        new_artist = None
        new_album = None
        artist_list = []
    
        with open("albums.txt","r") as albums:
            for line in albums:
                #data row should consist of (artist,album,year,song)
                artist_field,album_field,year_field,song_field = tuple(line.strip('\n').split('\t'))
                year_field = int(year_field)
                if new_artist is None:
                    new_artist = Artist(artist_field)
                    artist_list.append(new_artist)
                elif new_artist.name != artist_field:
                    #we have just read details for new artist
                    #check for the existence of the object
                    new_artist = checkobjectexist(artist_field,artist_list)
                    if new_artist is None:
                        new_artist = Artist(artist_field)
                        artist_list.append(new_artist)
                    new_album = None
    
                if new_album is None:
                    new_album = Album(album_field,year_field,new_artist)
                    new_artist.add_album(new_album)
                elif new_album.name != album_field:
                    #we have just read details for new album for the current artist
                    #check whether the album already exists in the list
                    new_album = checkobjectexist(album_field,new_artist.albums)
                    if new_album is None:
                        new_album = Album(album_field,year_field,new_artist)
                        new_artist.add_album(new_album)
    
            #create a new song object and add it to the current album's collection
                new_song = Song(song_field,new_artist)
                new_album.add_song(new_song)
    
        return artist_list
    
    # def create_checkfile(artist_list):
    #     """Create a check file from the object data for comparison with the original file"""
    #     with open("checkfile.txt", 'w') as checkfile:
    #         for new_artist in artist_list:
    #             for new_album in new_artist.albums:
    #                 for new_song in new_album.tracks:
    #                     print("{0.name}\t{1.name}\t{1.year}\t{2.title}".format(new_artist, new_album, new_song),
    #                           file=checkfile)
    
    
    
    if __name__ == '__main__':
        artists = load_data()
        print(len(artists))
    
        # for new_artist in artists:
        #     for new_album in new_artist.albums:
        #         print(new_album.name,new_album.tracks)
    # create_checkfile(artists)
    
     
    
  • The below program produces the same result,except that the concepts that are used like checking the existence of the artist and album are done inside the class
  •   
    class Song:
        """
        class to represent a song
    
        Attributes:
            title():The tile of the song
            artist(Artist):An artist object representing the songs creator
            duration (int):The duration of the song in seconds.May be Zero
        """
        def __init__(self,title,artist,duration=0):
            """song init method
            Args:
                title(str):Initialises the 'title' attribute
                artist(Artist):An artist object representing the songs creator
                duration (optional int):initialise value to 'duration' attribute
                        will be defaulted to zero if not specified.
            """
            self.name = title
            self.artist = artist
            self.duration = duration
    
    
    class Album:
        """ class to represent a album,using its track list
    
        Attributes:
            name (str):The name of the album.
            year (int):The year the album was released.
            artist :(Artist):The artist responsible for the album.If not specified,
            the artist will default to an artist with the name "Various Artists".
            tracks (List[Song]):A List of songs on the album
    
            Methods:
                add_song:used to add a new song to the albums track list
        """
    
        def __init__(self,name,year,artist =None):
            self.name = name
            self.year = year
            if artist is None:
                self.artist = Artist("Various artists")
            else:
                self.artist = artist
    
            self.tracks = []
    
        def add_song(self,songname,position = None):
            """Adds a song to the track list
    
            Args:
                song(Song):A song to add.
                position (optional[int]):If specified,the song will be added to that position
                    in the track list  - inserting it between other songs if necessary.
                    Otherwise,the song will be added to the end of tthe list
            """
            # print(self.name,self.tracks)
            # print('***')
            song_found = checkobjectexist(songname,self.tracks)
            # print('***')
            if song_found is None:
                song_found = Song(songname,self.artist)
                # print("Song Not Found")
                if position is None:
                    self.tracks.append(song_found)
                else:
                    self.tracks.insert(position,song_found)
    
    
    class Artist:
        """Basic class to store artist details
    
        Attributes:
            name(str):The name of the artist
            albums (List[Album]):A list of albums by this artist.
                    The list includes only those albums in this collection,it is
                    not an exhaustive list of the artist's published albums
    
        Methods:
            add_album:used to add a new album to the artists's album list
    
        """
    
        def __init__(self,name):
            self.name = name
            self.albums = []
    
        def add_album(self,album):
            """
            Add a new album to the list.
    
            Args:
                album(Album):Album object to add to the list.
                    If the album is already present,it will not be added again (although it is yet to be implemented).
            """
            self.albums.append(album)
    
        def add_song(self,album_name,year,song_name):
            album_found = checkobjectexist(album_name,self.albums)
            if album_found is None:
                # print("Album Not Found")
                album_found = Album(album_name,year,self)
                self.add_album(album_found)
            else:
                print("Found Album")
    
            album_found.add_song(song_name)
    
    def checkobjectexist (field,object_list):
        for item in object_list:
            if item.name == field:
                return item
        return None
    
    def load_data():
        artist_list = []
    
        with open("albums.txt","r") as albums:
            for line in albums:
                #data row should consist of (artist,album,year,song)
                artist_field,album_field,year_field,song_field = tuple(line.strip('\n').split('\t'))
                year_field = int(year_field)
    
                new_artist = checkobjectexist(artist_field,artist_list)
                if new_artist is None:
                    new_artist = Artist(artist_field)
                    artist_list.append(new_artist)
    
                new_artist.add_song(album_field,year_field,song_field)
    
        return artist_list
    
    # def create_checkfile(artist_list):
    #     """Create a check file from the object data for comparison with the original file"""
    #     with open("checkfile.txt", 'w') as checkfile:
    #         for new_artist in artist_list:
    #             for new_album in new_artist.albums:
    #                 for new_song in new_album.tracks:
    #                     print("{0.name}\t{1.name}\t{1.year}\t{2.title}".format(new_artist, new_album, new_song),
    #                           file=checkfile)
    
    
    
    if __name__ == '__main__':
        artists = load_data()
        print(len(artists))
    
        # for new_artist in artists:
        #     for new_album in new_artist.albums:
        #         print(new_album.name,new_album.tracks)
    # create_checkfile(artists)
    
     
    

    Sunday, 15 April 2018

    Python - OOPS Basics-eg1 - Day 25(4 days later)

  • simple program on bank account concept,based on oops
  •   
    import datetime
    import pytz
    class Account:
    
        #this will be static method,ie it will be common for all instances(ie the class)
        #so while accessing it no need of using self
        @staticmethod
        def _current_time():
            utc_time = datetime.datetime.utcnow()
            return pytz.utc.localize(utc_time)
    
    
    
        def __init__(self,name,_balance):
            self._name =name
            self._transactiondetails_list = [(Account._current_time(), _balance)]
            self._balance = _balance
            print("Account Created for {}".format(self._name))
            self.showbalance()
    
        def deposit(self,amount):
            self._balance+=amount
            self.showbalance()
            self._transactiondetails_list.append((Account._current_time(), amount))
            # self.transactiondetails_list.append((pytz.utc.localize(datetime.datetime.utcnow()),amount))
            # print(self.transactiondetails_list)
    
        def withdraw(self,amount):
            if(0 < amount<=self._balance):
                self._balance-=amount
                self._transactiondetails_list.append((Account._current_time(), -amount))
            else:
                print("Amount should be greater than 0 and lesser than available balance")
            self.showbalance()
    
        def showbalance(self):
            print('Balance: ', self._balance)
    
        def showtransdetails(self):
            for date, amount in self._transactiondetails_list:
                if amount > 0:
                    tran_type ='Deposited'
                else:
                    tran_type ='Withdrwan'
                    amount*=-1
                print("{:6} {} on {} (local time was {})".format(amount,tran_type,date,date.astimezone()))
    
    udai = Account('udai',1000)
    #udai.withdraw(100)
    # udai.withdraw(200)
    # udai.deposit(200)
    # #we can update the balance variable to whatever we want outside of the class,so we can rename
    # #to _balance,which will also dont restrict to change , but user can know that
    # #it is for internal purpose and shouldn't be modified,similarly for the name and list variables
    # #which should not be modified after the instantiation
    # # udai.balance=0
    # udai.showbalance()
    # udai.showtransdetails()
    
    #its better not to mess with '_' and '__' objects which will produce strange results
    udai.showbalance()
    udai._balance = 10
    udai.showbalance()
    print('*'*40)
    print(udai.__dict__)
    print(Account.__dict__)
    udai.__balance = 49
    udai.showbalance()
    udai.showbalance()
    print(udai.__dict__)
    print(Account.__dict__)
     
    

    Python - OOPS Basics - Day 25(4 days later)

  • Class:template for creating objects.All objects created using the same class will have the same charecteristics Objects:an instance of a class Instantiate:Create a Instance of a class Method:a funtion defined in a class Attribute:a variable bound to a instance of a class
  •   
    #everything is objects in python
    #take away : class and objects
    
    # a = 1
    # b = 3
    # print (a + b)
    # print (a.__add__(b))
    #so + is same as __add__ ,if u ctrl right click it will goto the same definition
    
    class kettle (object):
    
        power_source = 'fuel'
    
        def __init__(self,make,price):
            self.make = make
            self.price = price
            self.on = False
    
        def switch_on(self):
            self.on = True
    
    kenwoodobj = kettle('kenwood',25)
    hamilton = kettle('hamilton',30)
    
    print(kenwoodobj.make)
    print(hamilton.make)
    print(hamilton.price)
    hamilton.make = 'Hamiltoon'
    print(hamilton.make)
    print(kenwoodobj)
    
    print ('{}={},{}={}'.format(kenwoodobj.make,kenwoodobj.price,hamilton.make,hamilton.price))
    kenwoodobj1 = kenwoodobj
    print(id(kenwoodobj1))
    print(id(kenwoodobj))
    print(id(hamilton))
    print(id(hamilton.make))
    
    #we can call the object by
    #classname.objectname(instancename)
    #or
    #instancename.objectname()
    kettle.switch_on(hamilton)
    print(hamilton.make)
    print(hamilton.on)
    hamilton.on = False
    print(hamilton.on)
    hamilton.switch_on()
    print(hamilton.on)
    
    #this is called as instance variable,variable is only for this instance,not for the entire instances of the
    #class
    kenwoodobj.power = 1.5
    print(kenwoodobj.power)
    #if we try accessing the same variable for different instance,it will throw error
    # print(hamilton.power)
    
    print (kettle.power_source)
    print (kenwoodobj.power_source)
    print (hamilton.power_source)
    
    print(kettle.__dict__)
    print(kenwoodobj.__dict__)
    print(hamilton.__dict__)
    
    print ('*' * 80)
    
    # kettle.power_source = 'atomic'
    
    print (kettle.power_source)
    print (kenwoodobj.power_source)
    print (hamilton.power_source)
    
    print(kettle.__dict__)
    print(kenwoodobj.__dict__)
    print(hamilton.__dict__)
    
    print ('/' * 80)
    
    #if we assign the value for the calss attribute instance,it becomes instance vriable and remains
    #unaffected for the class and other instances
    kenwoodobj.power_source = 'gas'
    
    print (kettle.power_source)
    print (kenwoodobj.power_source)
    print (hamilton.power_source)
    
    print(kettle.__dict__)
    print(kenwoodobj.__dict__)
    print(hamilton.__dict__)
    
    print ('*' * 80)
    hamilton.power_source = 'fossil fuel'
    
    print (kettle.power_source)
    print (kenwoodobj.power_source)
    print (hamilton.power_source)
    
    print(kettle.__dict__)
    print(kenwoodobj.__dict__)
    print(hamilton.__dict__)
    
    hamilton.power_source = 'fuel'
    
    print (kettle.power_source)
    print (kenwoodobj.power_source)
    print (hamilton.power_source)
    
    print(kettle.__dict__)
    print(kenwoodobj.__dict__)
    print(hamilton.__dict__)
    
    print ('@' * 80)
    
    kettle.power_source = 'fuel'
    
    print (kettle.power_source)
    print (kenwoodobj.power_source)
    print (hamilton.power_source)
    
    print(kettle.__dict__)
    print(kenwoodobj.__dict__)
    print(hamilton.__dict__)
     
    
  • this will explain how a basic program document has to be written
  •   
    #this will explain you how to document a program(DocString)
    class song:
        """
        class to represent a song
    
        Attributes:
            title():The tile of the song
            artist(Artist):An artist object representing the songs creator
            duration (int):The duration of the song in seconds.May be Zero
        """
        def __int__(self,title,artist,duration=0):
            """song init method
            Args:
                title(str):Intialises the 'title' attribute
                artist(Artist):An artist object representing the songs creator
                duration (optional int):initialise value to 'duration' attribute
                        will be defaulted to zero if not specified.
    
    
            """
            self.title = title
            self.artist = artist
            self.duration = duration
     
    

    Python - scope and recursive function - Day 25(4 days later)

  • this will explain the variable's scope.
  •   
    #take way:read the document related to local,nonlocal,global
    #know what is LEGB - Local Enclosing Global Builtins
    #below example will illustrate the variable and the scope of it
    
    
    # def spam1():
    #     def spam2():
    #         def spam3():
    #             z = ' even more spam'
    #             print('3 {}'.format(locals()))
    #             return z
    #         y = 'more spam '
    #         y+= spam3()
    #         print('2 {}'.format(locals()))
    #         return y
    #     x = 'spam '
    #     x+= spam2()
    #     print('1 {}'.format(locals()))
    #     print(x)
    
    def spam1():
        def spam2():
            def spam3():
                # y = 'test'
                z = ' even' + y
                print('3 {}'.format(locals()))
                return z
            y = ' more'+x
            y+= spam3()
            print('2 {}'.format(locals()))
            return y
        x = 'spam'
        x+= spam2()
        # we can't write like this x = 'spam' + spam2(),since spam2 function first expects x
        # it will throw unreferenced variable error if we code like that
        print('1 {}'.format(locals()))
        print(x)
    
    print(spam1())
    print(locals())
    print(globals())
     
    
  • this will explain how the recursive funtion can be made use of
  •   
    #recursive function,function that calls itself again and again
    #factorial
    
    def factorial(n):
        result = 1
        if n>1:
            for i in range (1,n+1):
                result = result * i
        return result
    
    def factorialrec(n):
        #n factorial can also be defined as n * (n-1)!
        if n<=1:
            return 1
        else:
            return n * factorialrec(n-1)
    
    def fibonaccirec(n):
        # Fn = Fn-1 + Fn-2
        if n<2:
            return n
        else:
            return fibonaccirec(n-1)+fibonaccirec(n-2)
    
    def fibonacci(n):
        if n == 0:
            return 0
        if n == 1:
            return 1
        elif n==2:
            return 1
        else:
            n_minus1 = 1
            n_minus2 = 0
            for i in range(1,n):
                result = n_minus1+n_minus2
                n_minus2 = n_minus1
                n_minus1 = result
            return result
    
    
    
    
    # for x in range (1,130):
    #     print(x , factorial(x))
    
    # for x in range (1,130):
    #     print(x , factorialrec(x))
    
    # here use of the recursive funtion in calculating the fibonaaci
    #might slow downb the process,so we can go for direct method
    
    # for x in range (1,36):
    #     print(x , fibonaccirec(x))
    
    #below direct method will be fast
    for x in range (1,36):
        print(x , fibonacci(x))
     
    

    Monday, 9 April 2018

    Python - using underscore - Day 24

      
    #there is nothing like private or protected concept in python
    #if we want to treat something as private we can use underscore '_'
    # in front of the name,although it wont have any programming influence,
    # but for the users understanding,also the objects starting with '_' won't be
    # displayed if we use import *,although we can access using the modulename.objectname
    # import blackjacktest1
    # g = sorted(globals())
    # for x in g:
    #     print(x)
    # for x in globals():
    #     print(x)
    # print (__name__)
    # blackjacktest1.play()
    
    #if you rename by prefexing any of the funtion with '_' and check the below loop will not return
    #those funtions or objects
    
    from blackjacktest1 import *
    g = sorted(globals())
    for x in g:
        print(x)
    
    #we can use '_' or '__' as variable name, thoughh it is not the proper way of naming variable
    _ = 'a'
    print(_)
    __ = 'ab'
    print(__)
    
    personaldetails =('udai',23,'welcome')
    name,_,__ = personaldetails
    print(name,_,__)