Showing posts with label python_class. Show all posts
Showing posts with label python_class. Show all posts

Jan 11, 2019

Python Class methods static vs class

#class method demo
class Pets:
    name = "pet animals"

    @classmethod
    def about(cls):
        print("This class is about {}!".format(cls.name))
    
class Dogs(Pets):
    name = "'man's best friends'"

class Cats(Pets):
    name = "cats"

p = Pets() #parent class
p.about() #This class is about pet animals!

d = Dogs() #inherited class
d.about() #This class is about 'man's best friends'!

c = Cats() #inherited class
c.about() #This class is about cats!


#static method demo
class Pets:
    name = "pet animals"

    @staticmethod
    def about():
        print("This class is about {}!".format(Pets.name))   
    
class Dogs(Pets):
    name = "'man's best friends'"

class Cats(Pets):
    name = "cats"

p = Pets()
p.about() #This class is about pet animals!
d = Dogs() 
d.about() #This class is about pet animals!
c = Cats()
c.about() #This class is about pet animals!


Mar 11, 2013

Python Class and Object Example

Lets discuss the basic Object-Oriented concept of Class & Object in Python with a simple example.

Lets create a Person Class and create objects for the Person class.


Python_Class_Object.py (Copy the below snippet and run the program)

class Person:
    '''Represents a person.'''
    count = 0

    def __init__(self, name):
        '''Initializing data.'''
        self.name = name
        print('\n Initializing %s' % self.name)

        # To count the people
        Person.count += 1

    def displayName(self):
        ''' Saying Hello'''
        print('My name is %s.' % self.name)
    
    def count_people(self):
        '''Prints the count.'''
        if Person.count == 1:
            print('I am the only person here.')
        else:
            print('We have %d persons here.' % Person.count)

Winston = Person('Winston Churchil')
Winston.displayName()
Winston.count_people()

Abraham = Person('Abraham Lincoln')
Abraham.displayName()
Abraham.count_people()
	 



You may also wish to read Object Oriented Concepts in Python as mentioned :
Inheritance in Python