New-Style Classes Thomas Wouters XS4ALL #python.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

Developers Day 2002 Making classes look like types (and vice versa) Or…
Test-Driven Development and Refactoring CPSC 315 – Programming Studio.
CSE 332: C++ copy control I Copy Control (Part I) Copy control consists of 5 distinct operations –A copy constructor initializes an object by duplicating.
Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Chapter 10 Classes Continued
Computer Science 111 Fundamentals of Programming I Introduction to Programmer-Defined Classes.
Guide to Programming with Python
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Creational Patterns Making Objects The Smart Way Brent Ramerth Abstract Factory, Builder.
OOP Languages: Java vs C++
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 12: Adding Functionality to Your Classes.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
CSC 508 – Theory of Programming Languages, Spring, 2009 Week 3: Data Abstraction and Object Orientation.
A Simple Java Relational Database Thomas A. Bullinger March 20, 2001
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Chapter 11: Introduction to Classes. In this chapter you will learn about: – Classes – Basic class functions – Adding class functions – A case study involving.
Object Oriented Software Development
Introduction to OOP OOP = Object-Oriented Programming OOP is very simple in python but also powerful What is an object? data structure, and functions (methods)
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
CS451 - Lecture 2 1 CS451 Lecture 2: Introduction to Object Orientation Yugi Lee STB #555 (816) * Acknowledgement:
Class Builder Tutorial Presented By- Amit Singh & Sylendra Prasad.
Object-Oriented Programming Chapter Chapter
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
Digging into the GAT API Comparing C, C++ and Python API‘s Hartmut Kaiser
ISBN Object-Oriented Programming Chapter Chapter
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
ITF11006.NET Generics. Generics - Sample Recent Generics - Characteristics Performance Type Safety Binary Code Reuse Code Bloat Naming Guidelines.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 12 Inheritance and Class Design 1.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
Python Object Model Sambasiva Suda PyCon India. Agenda Python Classic Objects Different types of Objects Relationships among objects Q & A.
OBJECT ORIENTED PROGRAMMING. Design principles for organizing code into user-defined types Principles include: Encapsulation Inheritance Polymorphism.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Python C API overview References:
ISBN Chapter 12 Support for Object-Oriented Programming.
The Object-Oriented Thought Process Chapter 03
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Object-Oriented Programming (OOP) in Python
Andy Wang Object Oriented Programming in C++ COP 3330
Computer Science 111 Fundamentals of Programming I
Introduction to Classes
Chapter 12 Outline Overview of Object Database Concepts
This pointer, Dynamic memory allocation, Constructors and Destructor
Python Classes By Craig Pennell.
Introduction to Classes
Implementing Non-Static Features
Computer Science 111 Fundamentals of Programming I
CISC/CMPE320 - Prof. McLeod
Migrating to Object-Oriented Programs
Lecture 8 Object Oriented Programming (OOP)
Presentation transcript:

New-Style Classes Thomas Wouters XS4ALL #python

Overview Old situation –types, classes –shape of Python Type unification –subtyping –descriptors and properties –class- and static-methods Metaclasses

Old situation: types Python types implemented in C –C structs represent types –C function pointers define functionality –No real class data –C structs represent objects –All instance data in object structs –'Manual' attribute retrieval –Explicit methods

Old situation: Python classes Implemented in terms of Python types –"bolted on top" –'classes' and 'instances' as distinct types –C function pointers delegated to 'magic' methods to define behaviour –tp_getattro function searches base classes –Implicit methods from Python functions –Class and instance data in '__dict__' attribute

Old situation: limitations Python and C as two distinct worlds No real accessors No class/static methods No immutable classes Simplistic inheritance order Less control over behaviour

Old situation: consequences Interface-based functionality –informal interfaces rather than inheritance Containment rather than inheritance –inheritance is not always the answer Simple inheritance trees Easy to use

Type unification Allow (better) mingling of Python and C types (or classes) –bring C and Python closer __dict__ and inheritance for C types descriptors, properties, class/staticmethods for Python classes –subclassing C types in C –subclassing C types in Python Correct 'warts' in classic classes Generalize special cases

Type unification (2) Metaclasses: a new type of type Explicit base class: object –container of generic functionality Old-style classes for compatibility –hidden metaclass Translation from C function-pointers to Python __methods__ (slots) __dict__ for C types and __slots__ for Python classes

Subclassing Subclass C types from Python in the expected manner: class mylist(list): def __getitem__(self, i): try: return list.__getitem__(self, i) except IndexError: return None Resricted multiple inheritance Not always a good idea!

Subclassing (2) __new__, Python's constructor –called to construct (allocate) the object –static method, called with class as first argument –may return an existing value __slots__: store data almost like C would –no __dict__, less memory consumption

Immutable Python types class tristate(int): __slots__ = [] nstates = 3 def __new__(cls, state=0): state %= cls.nstates return int.__new__(cls, state) def __add__(self, o): return tristate(int.__add__(self, o)) def __sub__(self, other): return self.__add__(-other)

Subclassing C types in C Make sure base type supports subclassing –Py _Check(), Py _CheckExact() –PyMethodDef, PyMemberDef, PyGetSetDef –PyObject_GenericGetAttr as tp_getattro –no type-object hardcoding Subclass's PyType object –leave unchanged behaviour up to base type –set tp_base to base class –call base class's tp_init Provide compatible object struct

Type checking Type-checking is a necessary evil (in C) PyObject_TypeCheck() for inheritance-aware PythonC type check Define Py _Check() in terms of PyObject_TypeCheck() Define Py _CheckExact() as type-pointer comparison Use Py _CheckExact() for internal optimizations

PyList_Check*() #define PyList_Check(op) \ PyObject_TypeCheck(op, \ &PyList_Type) #define PyList_CheckExact(op)\ ((op)->ob_type == \ &PyList_Type)

Py*Def Allow subclasses to extend/override parts PyMemberDef (tp_members) for instance data –maps C structs to Python attributes –tp_members in type struct PyMethodDef (tp_methods) for all methods –wraps C functions in Python objects –specifies argument style and type of method PyGetSetDef (tp_getset) for accessors –maps functions to attributes and vice versa

Subclass struct Include base class struct in subclass struct typedef struct { PyListObject list; PyObject * default; } defaultlistobject; No changes to original memory layout Multiple inheritance is only possible with 'compatible memory layouts' C subclasses subclassable in Python

Method Resolution Order Old MRO not suited to complex inheritance trees –base classes get queried before some of their derived classes –base classes get queried multiple times –No convenient way to access base classes hardcode base class names guess about attributes / methods

New MRO Published algorithm: C3 – ion-oopsla96.htmlhttp:// ion-oopsla96.html Relatively easy to explain –same order as before –eliminates all but the last occurance of the same class Same order for simple inheritance

Old-style MRO: D, B, A, C, A New-style MRO: D, B, C, A (see __mro__) A D(B, C) C(A) B(A)

A D(B, C) C(A) B(A) E(C, B) F(D, E) Old-style MRO: F, D, B, A, C, A, E, C, A, B, A New-style MRO (2.2): F, D, E, B, C, A

super() Proxy'object for accessing 'base' classes Continues MRO where it left off –requires current class and (derived) instance Somewhat inconvenient to use Very important for consistency Use it anyway

super() use class BStore(Storage): def __init__(self, state): Storage.__init__(self, state) class BStore(Storage): def __init__(self, state): super(BStore, self).__init__(state)

Descriptors Generalization of class-getattr magic and C tp_getattr tricks Trigger functioncalls when retrieved or stored from an object (getattr/setattr) –__get__() –__set__() –__delete__()

Properties Accessors for Python An application of descriptors class R(object): def _get_random(self): return random.random() random = property(_get_random) Also hold docstrings for attributes 'set' and 'delete' functions don't work with old- style classes

Caching Property class cachingprop(object): __slots__ = ["_name", "_fget"] def __init__(self, name, fget): self._name = name self._fget = fget def __get__(self, inst, type=None): if inst is None: return self v = self._fget(inst) inst.__dict__[self._name] = v return v

Special method types classmethods –Passes class as implicit first argument –can be called through class or through instance –allow for factory functions (or 'alternate initializers') that create subclasses dict.fromkeys tarfile.TarFile.open

Special Method Types (2) staticmethods –Passes no special arguments –Necessary for object.__new__ (or is it?) –Allows for regular (non-method) Python functions as attributes

Special Method Types (3) class Buffer(object): def __init__(self, data): self.data = data[:] def fromstring(cls, s): return cls(s.splitlines()) fromstring = classmethod(fromstring) def send(self): self._extern_send(self.data) _extern_send = staticmethod(sendmodule.send)

Metaclasses The class of class Usually derives from type Relate to classes like classes relate to instances Define class behaviour Allow for convenient post-processing of classes

Class/instance relation Creating the instance passes the contents (arguments) to the class __init__: class Send(object): def __init__(self, what, who):... Send("my data", him)

Metaclass/class relation class Meta(type): def __init__(self, name, bases, attrs): type.__init__(self, name, bases, attrs) class Impl(base1, base2): __metaclass__ = Meta X = 1 def method(self, it): return not it stat = staticmethod(...)

Metaclasses Behave like classes: –__new__ called for class creation –__init__ called for class initialization –inheritance Mixing metaclasses requires compatibility –derived classes must have same or derived metaclasses –metametaclasses can automatically derive metaclasses

Questions ? Slides will be on