February 6, 2019

Python Classes and Objects

Defining & Operating on classes in Python

Python is an Object Oriented Programming (OOP) language.
To create a class in Python language, we have to use keyword class.

class ClassName(object): 
<statement-1> 
. . . 
<statement-N> 

class MyClass:
    x = 6

self parameter is a reference to the class instance itself, and is used to access variables that belongs to the class. Has to be the first parameter of any function in the class.

class Foo:
def __init__(self):
    self.member = 1
def GetMember(self):
    return self.member

class Movie:

def __init__(self, title_in, storyline, poster_img, trailer_url):
self.title = title_in # Instance Variable
self.story = storyline
self.poster = poster_img
self.trailer = trailer_url
def show_trailer(self):
webbrowser.open(self.trailer)

class DemoThread(threading.Thread):

    def run(self):
      for i in range(3):
         time.sleep(3)
         print i

We can use the class name to create objects.
>>> x = MyClass() # object is passed as first argument of function  'self'
new_movie = Movie('Avatar')
obj_p = PersonClass("Satya", 36)

print(new_movie.title)
print(new_phone.name, new_phone.is_ios, new_phone.size, new_phone.rating)

Python Class Inheritance:
class Parent():
....
class Child(Parent):
...

class MyClass(object): 
"""A simple example class. This is doc string.""" 
i = 12345
def f(self): 
return self.i

class DerivedClassName(BaseClassName): 
<statement-1> 
. . . 
<statement-N> 


Predefined Class Variables:
__init__ # Constructor - called automatically every time class is being used to create new object.
__del__ # Destructor
__doc__
MyClass.__doc__
__cmp__
__str__
__name__
__module__

isinstance(object, classinfo)
issubclass(class, classinfo)

type(instance_variable_name)

del obj # delete objects
del obj.prop # delete properties on objects

Related Python Articles: if else elif statements in Python  Functions in Python


No comments:

Post a Comment