Python allows importing and using classes and functions defined in other files through modules. There are three main ways to import modules: import somefile imports everything and requires prefixing names with the module name, from somefile import * imports everything without prefixes, and from somefile import className imports a specific class. Modules look for files in directories listed in sys.path.
Classes define custom data types by storing shared data and methods. Instances are created using class() and initialized with __init__. Self refers to the instance inside methods. Attributes store an instance's data while class attributes are shared. Inheritance allows subclasses to extend and redefine parent class features. Special built-in methods control class behaviors like string representation or iteration.
The document introduces Python modules and importing. It discusses three formats for importing modules: import somefile, from somefile import *, and from somefile import className. It describes commonly used Python modules like sys, os, and math. It also covers defining your own modules, directories for module files, object-oriented programming in Python including defining classes, creating and deleting instances, methods and self, accessing attributes and methods, attributes, inheritance, and redefining methods.
Python supports object-oriented programming through classes, objects, and related concepts like inheritance, polymorphism, and encapsulation. A class acts as a blueprint to create object instances. Objects contain data fields and methods. Inheritance allows classes to inherit attributes and behaviors from parent classes. Polymorphism enables the same interface to work with objects of different types. Encapsulation helps protect data by restricting access.
This document discusses object-oriented programming concepts in Python including:
- Classes define templates for objects with attributes and methods. Objects are instances of classes.
- The __init__ method initializes attributes when an object is constructed.
- Classes can make attributes private using double underscores. Encapsulation hides implementation details.
- Objects can be mutable, allowing state changes, or immutable like strings which cannot change.
- Inheritance allows subclasses to extend and modify parent class behavior through polymorphism.
در این جلسه به بررسی بحث برنامه نویسی شی گرا و کلاس ها در پایتون پرداختیم
PySec101 Fall 2013 J7E1 By Mohammad Reza Kamalifard
Talk About:
Object oriented programming and Classes in Python
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
The document discusses object oriented programming concepts in Python including classes, objects, instances, methods, inheritance, and class attributes. It provides examples of defining classes, instantiating objects, using methods, and the difference between class and instance attributes. Key concepts covered include defining classes with the class keyword, creating object instances, using the __init__() method for initialization, and allowing derived classes to inherit from base classes.
This document discusses Python modules, classes, inheritance, and properties. Some key points:
- Modules allow the organization of Python code into reusable libraries by saving code in files with a .py extension. Modules can contain functions, variables, and be imported into other code.
- Classes are templates that define the properties and methods common to all objects of a certain kind. The __init__() method initializes new objects. Inheritance allows child classes to inherit properties and methods from parent classes.
- Properties provide a way to control access to class attributes, allowing them to be accessed like attributes while hiding the implementation details behind getter and setter methods.
This document discusses object-oriented programming concepts in Python including classes, objects, attributes, methods, inheritance, polymorphism, and special methods. Key points include:
- Classes are templates that define objects, while objects are instantiations of classes with unique attribute values.
- Methods define object behaviors. The self parameter refers to the current object instance.
- Inheritance allows classes to extend existing classes, reusing attributes and methods from parent classes.
- Special methods with double underscores have predefined meanings (e.g. __init__ for constructors, __repr__ for string representation).
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
Class, object and inheritance in pythonSantosh Verma
The document discusses object-oriented programming concepts in Python, including classes, objects, methods, inheritance, and the built-in __init__ method. Classes are created using the class keyword and contain attributes and methods. Methods must have a self parameter, which refers to the instance of the class. The __init__ method is similar to a constructor and is called when an object is instantiated. Inheritance allows one class to inherit attributes and methods from another class.
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov
Classes allow users to create custom types in Python. A class defines the form and behavior of a custom type using methods. Objects or instances are created from a class and can have their own state and values. Common class methods include __init__() for initializing objects and setting initial values, and other methods like set_age() for modifying object attributes. Classes can inherit behaviors from superclasses and override existing methods.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
The document discusses various advanced Python concepts including classes, exception handling, generators, CGI, databases, Tkinter for GUI, regular expressions, and email sending using SMTP. It covers object-oriented programming principles like inheritance, encapsulation, and polymorphism in Python. Specific Python concepts like creating and accessing class attributes, instantiating objects, method overloading, operator overloading, and inheritance are explained through examples. The document also discusses generator functions and expressions for creating iterators in Python in a memory efficient way.
The document discusses object-oriented programming concepts in Python like classes, objects, inheritance, polymorphism, and multiple inheritance. It provides examples of defining classes with methods and instantiating objects. Inheritance allows deriving a child class from a parent class to inherit attributes and methods. Methods can be overridden in the child class. Super() is used to explicitly call the parent class's method. Multiple inheritance allows a class to inherit from multiple parent classes.
The document discusses Python classes and object-oriented programming concepts. It defines key terms like class, object, method, and inheritance. It provides examples of creating a basic Employee class with methods and instance variables. It also covers class variables, accessing object attributes, adding/removing attributes, inheritance, and overriding methods in subclasses. The goal is to teach Python language essentials for object-oriented programming.
The document discusses object-oriented programming concepts in Python like classes, objects, inheritance and polymorphism.
Some key points:
- Classes define the structure and behavior of an object using methods and attributes.
- Objects are instances of a class that contain data and allow methods to operate on that data.
- Inheritance allows a derived/child class to inherit attributes and methods from a base/parent class. The derived class can override or extend the parent class.
- Polymorphism allows derived classes to define their own implementation of a method while reusing the parent's implementation.
The document discusses object-oriented programming concepts in Python like classes, objects, methods, variables, inheritance and polymorphism. It provides examples of how to define a class with attributes and methods, create objects, and access variables and call methods. It also explains different types of methods like instance methods, class methods, static methods and variable types like instance and static/class variables. Inheritance allows creating new classes from existing classes for code reusability.
The document defines key object-oriented programming concepts like classes, objects, inheritance, polymorphism, encapsulation and abstraction.
It explains that a class is a logical grouping of attributes and methods, an object is an instance of a class, and object instantiation is the process of creating an object. It discusses self parameter, init methods, class attributes, instance attributes, static and instance methods.
It describes inheritance, multiple and multilevel inheritance. It covers abstraction, encapsulation, polymorphism and operator overloading. It also discusses naming conventions, abstract base classes, overriding and the use of super().
Class is a blueprint for creating objects with common attributes and behaviors. To define a class, use the class keyword followed by the class name. Self refers to the instance of the class. Objects are created by calling the class and passing arguments to its __init__ method. Attributes of an object can be accessed using the dot operator with the object, while class variables use the class name.
This document discusses Python modules, classes, inheritance, and properties. Some key points:
- Modules allow the organization of Python code into reusable libraries by saving code in files with a .py extension. Modules can contain functions, variables, and be imported into other code.
- Classes are templates that define the properties and methods common to all objects of a certain kind. The __init__() method initializes new objects. Inheritance allows child classes to inherit properties and methods from parent classes.
- Properties provide a way to control access to class attributes, allowing them to be accessed like attributes while hiding the implementation details behind getter and setter methods.
This document discusses object-oriented programming concepts in Python including classes, objects, attributes, methods, inheritance, polymorphism, and special methods. Key points include:
- Classes are templates that define objects, while objects are instantiations of classes with unique attribute values.
- Methods define object behaviors. The self parameter refers to the current object instance.
- Inheritance allows classes to extend existing classes, reusing attributes and methods from parent classes.
- Special methods with double underscores have predefined meanings (e.g. __init__ for constructors, __repr__ for string representation).
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
Class, object and inheritance in pythonSantosh Verma
The document discusses object-oriented programming concepts in Python, including classes, objects, methods, inheritance, and the built-in __init__ method. Classes are created using the class keyword and contain attributes and methods. Methods must have a self parameter, which refers to the instance of the class. The __init__ method is similar to a constructor and is called when an object is instantiated. Inheritance allows one class to inherit attributes and methods from another class.
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov
Classes allow users to create custom types in Python. A class defines the form and behavior of a custom type using methods. Objects or instances are created from a class and can have their own state and values. Common class methods include __init__() for initializing objects and setting initial values, and other methods like set_age() for modifying object attributes. Classes can inherit behaviors from superclasses and override existing methods.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
The document discusses various advanced Python concepts including classes, exception handling, generators, CGI, databases, Tkinter for GUI, regular expressions, and email sending using SMTP. It covers object-oriented programming principles like inheritance, encapsulation, and polymorphism in Python. Specific Python concepts like creating and accessing class attributes, instantiating objects, method overloading, operator overloading, and inheritance are explained through examples. The document also discusses generator functions and expressions for creating iterators in Python in a memory efficient way.
The document discusses object-oriented programming concepts in Python like classes, objects, inheritance, polymorphism, and multiple inheritance. It provides examples of defining classes with methods and instantiating objects. Inheritance allows deriving a child class from a parent class to inherit attributes and methods. Methods can be overridden in the child class. Super() is used to explicitly call the parent class's method. Multiple inheritance allows a class to inherit from multiple parent classes.
The document discusses Python classes and object-oriented programming concepts. It defines key terms like class, object, method, and inheritance. It provides examples of creating a basic Employee class with methods and instance variables. It also covers class variables, accessing object attributes, adding/removing attributes, inheritance, and overriding methods in subclasses. The goal is to teach Python language essentials for object-oriented programming.
The document discusses object-oriented programming concepts in Python like classes, objects, inheritance and polymorphism.
Some key points:
- Classes define the structure and behavior of an object using methods and attributes.
- Objects are instances of a class that contain data and allow methods to operate on that data.
- Inheritance allows a derived/child class to inherit attributes and methods from a base/parent class. The derived class can override or extend the parent class.
- Polymorphism allows derived classes to define their own implementation of a method while reusing the parent's implementation.
The document discusses object-oriented programming concepts in Python like classes, objects, methods, variables, inheritance and polymorphism. It provides examples of how to define a class with attributes and methods, create objects, and access variables and call methods. It also explains different types of methods like instance methods, class methods, static methods and variable types like instance and static/class variables. Inheritance allows creating new classes from existing classes for code reusability.
The document defines key object-oriented programming concepts like classes, objects, inheritance, polymorphism, encapsulation and abstraction.
It explains that a class is a logical grouping of attributes and methods, an object is an instance of a class, and object instantiation is the process of creating an object. It discusses self parameter, init methods, class attributes, instance attributes, static and instance methods.
It describes inheritance, multiple and multilevel inheritance. It covers abstraction, encapsulation, polymorphism and operator overloading. It also discusses naming conventions, abstract base classes, overriding and the use of super().
Class is a blueprint for creating objects with common attributes and behaviors. To define a class, use the class keyword followed by the class name. Self refers to the instance of the class. Objects are created by calling the class and passing arguments to its __init__ method. Attributes of an object can be accessed using the dot operator with the object, while class variables use the class name.
Different pricelists for different shops in odoo Point of Sale in Odoo 17Celine George
Price lists are a useful tool for managing the costs of your goods and services. This can assist you in working with other businesses effectively and maximizing your revenues. Additionally, you can provide your customers discounts by using price lists.
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...parmarjuli1412
The document provides an overview of therapeutic communication, emphasizing its importance in nursing to address patient needs and establish effective relationships. THERAPEUTIC COMMUNICATION included some topics like introduction of COMMUNICATION, definition, types, process of communication, definition therapeutic communication, goal, techniques of therapeutic communication, non-therapeutic communication, few ways to improved therapeutic communication, characteristics of therapeutic communication, barrier of THERAPEUTIC RELATIONSHIP, introduction of interpersonal relationship, types of IPR, elements/ dynamics of IPR, introduction of therapeutic nurse patient relationship, definition, purpose, elements/characteristics , and phases of therapeutic communication, definition of Johari window, uses, what actually model represent and its areas, THERAPEUTIC IMPASSES and its management in 5th semester Bsc. nursing and 2nd GNM students
HOW YOU DOIN'?
Cool, cool, cool...
Because that's what she said after THE QUIZ CLUB OF PSGCAS' TV SHOW quiz.
Grab your popcorn and be seated.
QM: THARUN S A
BCom Accounting and Finance (2023-26)
THE QUIZ CLUB OF PSGCAS.
This presentation has been made keeping in mind the students of undergraduate and postgraduate level. To keep the facts in a natural form and to display the material in more detail, the help of various books, websites and online medium has been taken. Whatever medium the material or facts have been taken from, an attempt has been made by the presenter to give their reference at the end.
In the seventh century, the rule of Sindh state was in the hands of Rai dynasty. We know the names of five kings of this dynasty- Rai Divji, Rai Singhras, Rai Sahasi, Rai Sihras II and Rai Sahasi II. During the time of Rai Sihras II, Nimruz of Persia attacked Sindh and killed him. After the return of the Persians, Rai Sahasi II became the king. After killing him, one of his Brahmin ministers named Chach took over the throne. He married the widow of Rai Sahasi and became the ruler of entire Sindh by suppressing the rebellions of the governors.
IDSP is a disease surveillance program in India that aims to strengthen/maintain decentralized laboratory-based IT enabled disease surveillance systems for epidemic prone diseases to monitor disease trends, and to detect and respond to outbreaks in the early phases swiftly.....
How to Create Time Off Request in Odoo 18 Time OffCeline George
Odoo 18 provides an efficient way to manage employee leave through the Time Off module. Employees can easily submit requests, and managers can approve or reject them based on company policies.
How to Create a Rainbow Man Effect in Odoo 18Celine George
In Odoo 18, the Rainbow Man animation adds a playful and motivating touch to task completion. This cheerful effect appears after specific user actions, like marking a CRM opportunity as won. It’s designed to enhance user experience by making routine tasks more engaging.
Strengthened Senior High School - Landas Tool Kit.pptxSteffMusniQuiballo
Landas Tool Kit is a very helpful guide in guiding the Senior High School students on their SHS academic journey. It will pave the way on what curriculum exits will they choose and fit in.
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...EduSkills OECD
Deborah Nusche, Senior Analyst, OECD presents at the OECD webinar 'Trends Spotting: Strategic foresight for tomorrow’s education systems' on 5 June 2025. You can check out the webinar on the website https://oecdedutoday.com/webinars/ Other speakers included: Deborah Nusche, Senior Analyst, OECD
Sophie Howe, Future Governance Adviser at the School of International Futures, first Future Generations Commissioner for Wales (2016-2023)
Davina Marie, Interdisciplinary Lead, Queens College London
Thomas Jørgensen, Director for Policy Coordination and Foresight at European University Association
Parenting Teens: Supporting Trust, resilience and independencePooky Knightsmith
For more information about my speaking and training work, visit: https://www.pookyknightsmith.com/speaking/
SESSION OVERVIEW:
Parenting Teens: Supporting Trust, Resilience & Independence
The teenage years bring new challenges—for teens and for you. In this practical session, we’ll explore how to support your teen through emotional ups and downs, growing independence, and the pressures of school and social life.
You’ll gain insights into the teenage brain and why boundary-pushing is part of healthy development, along with tools to keep communication open, build trust, and support emotional resilience. Expect honest ideas, relatable examples, and space to connect with other parents.
By the end of this session, you will:
• Understand how teenage brain development affects behaviour and emotions
• Learn ways to keep communication open and supportive
• Explore tools to help your teen manage stress and bounce back from setbacks
• Reflect on how to encourage independence while staying connected
• Discover simple strategies to support emotional wellbeing
• Share experiences and ideas with other parents
Pests of Rice: Damage, Identification, Life history, and Management.pptxArshad Shaikh
Rice pests can significantly impact crop yield and quality. Major pests include the brown plant hopper (Nilaparvata lugens), which transmits viruses like rice ragged stunt and grassy stunt; the yellow stem borer (Scirpophaga incertulas), whose larvae bore into stems causing deadhearts and whiteheads; and leaf folders (Cnaphalocrocis medinalis), which feed on leaves reducing photosynthetic area. Other pests include rice weevils (Sitophilus oryzae) and gall midges (Orseolia oryzae). Effective management strategies are crucial to minimize losses.
"Hymenoptera: A Diverse and Fascinating Order".pptxArshad Shaikh
Hymenoptera is a diverse order of insects that includes bees, wasps, ants, and sawflies. Characterized by their narrow waists and often social behavior, Hymenoptera play crucial roles in ecosystems as pollinators, predators, and decomposers, with many species exhibiting complex social structures and communication systems.
Analysis of Quantitative Data Parametric and non-parametric tests.pptxShrutidhara2
This presentation covers the following points--
Parametric Tests
• Testing the Significance of the Difference between Means
• Analysis of Variance (ANOVA) - One way and Two way
• Analysis of Co-variance (One-way)
Non-Parametric Tests:
• Chi-Square test
• Sign test
• Median test
• Sum of Rank test
• Mann-Whitney U-test
Moreover, it includes a comparison of parametric and non-parametric tests, a comparison of one-way ANOVA, two-way ANOVA, and one-way ANCOVA.
2. IT
IT’
’S ALL OBJECTS…
S ALL OBJECTS…
Everything in Python is really an object.
We’ve seen hints of this already…
“hello”.upper()
list3.append(‘a’)
dict2.keys()
New object classes can easily be defined
in addition to these built-in data-types.
In fact, programming in Python is typically
done in an object oriented fashion.
3. DEFINING A CLASS
DEFINING A CLASS
A class is a special data type which defines
how to build a certain kind of object.
The class also stores some data items that
are shared by all the instances of this class
Instances are objects that are created which
follow the definition given inside of the class
Python doesn’t use separate class interface
definitions as in some languages. You just
define the class and then use it
4. METHODS IN CLASSES
METHODS IN CLASSES
Define a method in a class by including
function definitions within the scope of the
class block
There must be a special first argument
self in all of method definitions which gets
bound to the calling instance
There is usually a special method called
__init__ in most classes
We’ll talk about both later…
5. A SIMPLE CLASS DEF:
A SIMPLE CLASS DEF: STUDENT
STUDENT
class student:
“““A class representing a
student ”””
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age
7. INSTANTIATING OBJECTS
INSTANTIATING OBJECTS
There is no “new” keyword as in Java.
Just use the class name with ( ) notation and
assign the result to a variable
__init__ serves as a constructor for the
class. Usually does some initialization work
The arguments passed to the class name are
given to its __init__() method
So, the __init__ method for student is passed
“Bob” and 21 and the new class instance is
bound to b:
b = student(“Bob”, 21)
8. CONSTRUCTOR: __INIT__
CONSTRUCTOR: __INIT__
An __init__ method can take any number
of arguments.
Like other functions or methods, the
arguments can be defined with default
values, making them optional to the caller.
However, the first argument self in the
definition of __init__ is special…
9. SELF
SELF
The first argument of every method is a
reference to the current instance of the class
By convention, we name this argument
self
In __init__, self refers to the object
currently being created; so, in other class
methods, it refers to the instance whose
method was called
10. SELF
SELF
Although you must specify self explicitly
when defining the method, you don’t
include it when calling the method.
Python passes it for you automatically
Defining a method: Calling a
method:
(this code inside a class definition.)
def set_age(self, num): >>> x.set_age(23)
self.age = num
11. DELETING INSTANCES: NO NEED
DELETING INSTANCES: NO NEED
TO
TO “
“FREE
FREE”
”
When you are done with an object, you don’t
have to delete or free it explicitly.
Python has automatic garbage collection.
Python will automatically detect when all of
the references to a piece of memory have
gone out of scope. Automatically frees that
memory.
There’s also no “destructor” method for
classes
13. DEFINITION OF STUDENT
DEFINITION OF STUDENT
class student:
“““A class representing a student
”””
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age
14. TRADITIONAL SYNTAX FOR ACCESS
TRADITIONAL SYNTAX FOR ACCESS
>>> f = student(“Bob Smith”, 23)
>>> f.full_name # Access attribute
“Bob Smith”
>>> f.get_age() # Access a method
23
15. ACCESSING UNKNOWN MEMBERS
ACCESSING UNKNOWN MEMBERS
Problem: Occasionally the name of an attribute
or method of a class is only given at run time…
Solution:
getattr(object_instance, string)
string is a string which contains the name of an
attribute or method of a class
getattr(object_instance, string)
returns a reference to that attribute or method
16. GETATTR(OBJECT_INSTANCE,
GETATTR(OBJECT_INSTANCE,
STRING)
STRING)
>>> f = student(“Bob Smith”, 23)
>>> getattr(f, “full_name”)
“Bob Smith”
>>> getattr(f, “get_age”)
<method get_age of class
studentClass at 010B3C2>
>>> getattr(f, “get_age”)() # call it
23
>>> getattr(f, “get_birthday”)
# Raises AttributeError – No method!
19. TWO KINDS OF ATTRIBUTES
TWO KINDS OF ATTRIBUTES
The non-method data stored by objects are
called attributes
Data attributes
Variable owned by a particular instance of a
class
Each instance has its own value for it
These are the most common kind of attribute
Class attributes
Owned by the class as a whole
All class instances share the same value for it
Called “static” variables in some languages
20. DATA ATTRIBUTES
DATA ATTRIBUTES
Data attributes are created and initialized
by an __init__() method.
Simply assigning to a name creates the
attribute
Inside the class, refer to data attributes using
self
for example, self.full_name
class teacher:
“A class representing teachers.”
def __init__(self,n):
self.full_name = n
def print_name(self):
print self.full_name
21. CLASS ATTRIBUTES
CLASS ATTRIBUTES
Because all instances of a class share one copy of a
class attribute, when any instance changes it, the
value is changed for all instances
Class attributes are defined within a class definition
and outside of any method
Since there is one of these attributes per class and
not one per instance, they’re accessed via a different
notation:
Access class attributes using self.__class__.name
notation -- This is just one way to do this & the safest in general.
class sample: >>> a = sample()
x = 23 >>> a.increment()
def increment(self): >>> a.__class__.x
self.__class__.x += 1 24
22. DATA VS. CLASS ATTRIBUTES
DATA VS. CLASS ATTRIBUTES
class counter:
overall_total = 0
# class attribute
def __init__(self):
self.my_total = 0
# data attribute
def increment(self):
counter.overall_total =
counter.overall_total + 1
self.my_total =
self.my_total + 1
>>> a = counter()
>>> b = counter()
>>> a.increment()
>>> b.increment()
>>> b.increment()
>>> a.my_total
1
>>> a.__class__.overall_total
3
>>> b.my_total
2
>>> b.__class__.overall_total
3
24. SUBCLASSES
SUBCLASSES
Classes can extend the definition of
other classes
Allows use (or extension) of methods and
attributes already defined in the previous
one
To define a subclass, put the name of
the superclass in parens after the
subclass’s name on the first line of the
definition
Class Cs_student(student):
Multiple inheritance is supported
25. REDEFINING METHODS
REDEFINING METHODS
To redefine a method of the parent class,
include a new definition using the same
name in the subclass
The old code won’t get executed
To execute the method in the parent class in
addition to new code for some method,
explicitly call the parent’s version of method
parentClass.methodName(self,a,b,c)
The only time you ever explicitly pass ‘self’ as
an argument is when calling a method of an
ancestor
26. DEFINITION OF A CLASS EXTENDING
DEFINITION OF A CLASS EXTENDING
STUDENT
STUDENT
Class Student:
“A class representing a student.”
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age
Class Cs_student (student):
“A class extending student.”
def __init__(self,n,a,s):
student.__init__(self,n,a) #Call __init__ for student
self.section_num = s
def get_age(): #Redefines get_age method entirely
print “Age: ” + str(self.age)
27. EXTENDING __INIT__
EXTENDING __INIT__
Same as redefining any other method…
Commonly, the ancestor’s __init__ method
is executed in addition to new commands
You’ll often see something like this in the
__init__ method of subclasses:
parentClass.__init__(self, x, y)
where parentClass is the name of the parent’s
class
29. BUILT-IN MEMBERS OF CLASSES
BUILT-IN MEMBERS OF CLASSES
Classes contain many methods and
attributes that are always included
Most define automatic functionality
triggered by special operators or usage
of that class
Built-in attributes define information
that must be stored for all classes.
All built-in members have double
underscores around their names:
__init__ __doc__
30. SPECIAL METHODS
SPECIAL METHODS
E.g., the method __repr__ exists for all
classes, and you can always redefine it
__repr__ specifies how to turn an
instance of the class into a string
print f sometimes calls f.__repr__()
to produce a string for object f
Typing f at the REPL prompt calls
__repr__ to determine what to display as
output
31. SPECIAL METHODS – EXAMPLE
SPECIAL METHODS – EXAMPLE
class student:
...
def __repr__(self):
return “I’m named ” + self.full_name
...
>>> f = student(“Bob Smith”, 23)
>>> print f
I’m named Bob Smith
>>> f
“I’m named Bob Smith”
32. SPECIAL METHODS
SPECIAL METHODS
You can redefine these as well:
__init__ : The constructor for the class
__cmp__ : Define how == works for class
__len__ : Define how len( obj ) works
__copy__ : Define how to copy a class
Other built-in methods allow you to give a
class the ability to use [ ] notation like an
array or ( ) notation like a function call
33. SPECIAL DATA ITEMS
SPECIAL DATA ITEMS
These attributes exist for all classes.
__doc__ : Variable for documentation string
for class
__class__ : Variable which gives you a reference
to the class from any instance of it
__module__ : Variable which gives a reference to
the module in which the particular class is defined
__dict__ :The dictionary that is actually the
namespace for a class (but not its superclasses)
Useful:
dir(x) returns a list of all methods and
attributes defined for object x
34. SPECIAL DATA ITEMS – EXAMPLE
SPECIAL DATA ITEMS – EXAMPLE
>>> f = student(“Bob Smith”, 23)
>>> print f.__doc__
A class representing a student.
>>> f.__class__
< class studentClass at 010B4C6 >
>>> g = f.__class__(“Tom Jones”,
34)
35. PRIVATE DATA AND
PRIVATE DATA AND
METHODS
METHODS
Any attribute/method with two leading
under-scores in its name (but none at the
end) is private and can’t be accessed
outside of class
Note: Names with two underscores at the
beginning and the end are for built-in
methods or attributes for the class
Note: There is no ‘protected’ status in
Python; so, subclasses would be unable to
access these private data either