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.
Search Engine Optimization (SEO) for Website SuccessMuneeb Rana
Unlock the essentials of Search Engine Optimization (SEO) with this concise, visually driven PowerPoint. Inside you’ll find:
✅ Clear definitions and core concepts of SEO
✅ A breakdown of On‑Page, Off‑Page, and Technical SEO
✅ Actionable best‑practice checklists for keyword research, content optimization, and link building
✅ A quick‑start toolkit featuring Google Analytics, Search Console, Ahrefs, SEMrush, and Moz
✅ Real‑world case study demonstrating a 70 % organic‑traffic lift
✅ Common challenges, algorithm updates, and tips for long‑term success
Whether you’re a digital‑marketing student, small‑business owner, or PR professional, this deck will help you boost visibility, build credibility, and drive sustainable traffic. Download, share, and start optimizing today!
RE-LIVE THE EUPHORIA!!!!
The Quiz club of PSGCAS brings to you a fun-filled breezy general quiz set from numismatics to sports to pop culture.
Re-live the Euphoria!!!
QM: Eiraiezhil R K,
BA Economics (2022-25),
The Quiz club of PSGCAS
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.
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.
How to Create a Stage or a Pipeline in Odoo 18 CRMCeline George
In Odoo, the CRM (Customer Relationship Management) module’s pipeline is a visual representation of a company's sales process that helps sales teams track and manage their interactions with potential customers.
How to Manage Maintenance Request in Odoo 18Celine George
Efficient maintenance management is crucial for keeping equipment and work centers running smoothly in any business. Odoo 18 provides a Maintenance module that helps track, schedule, and manage maintenance requests efficiently.
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxArshad Shaikh
Diptera, commonly known as flies, is a large and diverse order of insects that includes mosquitoes, midges, gnats, and horseflies. Characterized by a single pair of wings (hindwings are modified into balancing organs called halteres), Diptera are found in almost every environment and play important roles in ecosystems as pollinators, decomposers, and food sources. Some species, however, are significant pests and disease vectors, transmitting diseases like malaria, dengue, and Zika virus.
Smart Borrowing: Everything You Need to Know About Short Term Loans in Indiafincrifcontent
Short term loans in India are becoming a go-to financial solution for individuals needing quick access to funds without long-term commitments. With fast approval, minimal documentation, and flexible tenures, these loans are ideal for handling emergencies, unexpected bills, or short-term goals. Understanding key aspects like short term loan features, eligibility, required documentation, and how to apply for a short term loan can help borrowers make informed decisions. Whether you're salaried or self-employed, short term loans offer convenience and speed. This guide walks you through the essentials so you can secure the right loan at the right time.
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.
A short update and next week. I am writing both Session 9 and Orientation S1.
As a Guest Student,
You are now upgraded to Grad Level.
See Uploads for “Student Checkin” & “S8”. Thx.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course (As a package). I’m Fusing both together.
This will include the foundation of each practice. Our Free Workshops can be used with any Reiki Yoga training package. Traditional Reiki does host rules and ethics. Its silent and within the JP Culture/Area/Training/Word of Mouth. It allows remote healing but there’s limits As practitioners and masters. We are not allowed to share certain secrets/tools. Some content is designed only for “Masters”. Some yoga are similar like the Kriya Yoga-Church (Vowed Lessons). We will review both Reiki and Yoga (Master tools) in the Course upcoming.
Session Practice, For Reference:
Before starting a session, Make sure to check your environment. Nothing stressful. Later, You can decorate a space as well.
Check the comfort level, any needed resources (Yoga/Reiki/Spa Props), or Meditation Asst?
Props can be oils, sage, incense, candles, crystals, pillows, blankets, yoga mat, any theme applies.
Select your comfort Pose. This can be standing, sitting, laying down, or a combination.
Monitor your breath. You can add exercises.
Add any mantras or affirmations. This does aid mind and spirit. It helps you to focus.
Also you can set intentions using a candle.
The Yoga-key is balancing mind, body, and spirit.
Finally, The Duration can be long or short.
Its a good session base for any style.
Next Week’s Focus:
A continuation of Intuition Development. We will review the Chakra System - Our temple. A misguided, misused situation lol. This will also serve Attunement later.
For Sponsor,
General updates,
& Donations:
Please visit:
https://ldmchapels.weebly.com
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.
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