Class members are public and class member functions are virtual Classes are objects
Types and classes are essentially the same thing, but the keywords
type and class do different things
class creates new types/classestype is a function that prints the
type/class of an objectObject-oriented programming is based on encapsulation
Methods are the functions inside of a class
class MyClass:
def f(self):
x = MyClass
x.f The function f created from MyClass is
a function object x.f is
a method object
xf = x.fMethods can call other methods in the same class They can also references things in the global scope
Attributes are the variables inside of a class
You access both of these with a period
class MyClass:
...
x = MyClass()MyClassxA priori, the nwew instance of the class MyClass will be empty
__init__ to
change thatclass Dog:
tricks = [] # mistaken use of a class variable
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick)
d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')
>>> d.tricks # unexpectedly shared by all dogs
['roll over', 'play dead']The problem here is that the tricks
list is a class variable, and thus will be shared by all instances of
the class
tricks in any
instance of the class, it will modify all of themInstead if we move the variable to the instance
__init__ will create a new instance variable,
using self.tricksclass Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # creates a new empty list for each dog
def add_trick(self, trick):
self.tricks.append(trick)
d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')
>>> d.tricks # unexpectedly shared by all dogs
['roll over', 'play dead']class DerivedClassName(BaseClassName):Given one class, we can create a new derived class from it
BaseClassName.methodnameYou can actually create a derived class that's built off of multiple base classes
class DerivedClassName(Base1, Base2):When searched for attributes this will
DerivedClassNameBase1 (including
any base classes, if Base1 is itself
derived)Base2It uses the call-next-method
Python has no private variables
The convention is to prefix with an underscore
_privVarName mangling
_spam becomes _classname__spam__init__This puts a newly created instance of the class into a specific initial state
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(1,1) __iter__This method returns a new iterator object that has the method __next__
There is also a built-in iter
function, which is called by any for loop
If you add the iter method to a class
__next__ method__next__Returns the next item from an iterator object
If there are no more items, it raises the StopIteration exception
class MyClass:
def __init__(self,data):
self.data = data
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index == len(data):
raise StopIteration
self.index - self.index + 1
return self.data[self.index - 1] __dict__Stores an object's writable attributes
def funct():
class C:
print(funct.__dict__)
print(C.__dict__)
dict allows you to add new attributes to an object
__slots__Very similar to dict, but it's a static type, rather than dynamic
class C:
__slots__ = ...
__add__a + b is interpretted as a.__add__(b)
__radd__If we try
int.__add(1, x)
for an object x, we'll get a NotImplemented error
but python will always check addition in the reverse order if NotImplemented shows up
this is done with the radd method
it will call
__radd__(x,1)
So if we define an addition method on type(x), we can then define
def __radd__(self, other):
return self + other
(assuming addition is commutative)
__call__This is used to make an object behave like a function
f(x) becomes the syntax for
f.__call__(x)
__eq__Used to define when two objects of the same class are equal
__enter__Used in context managers When it's called, you enter the runtime context of the object
__exit__Exits the runtime context of the object
Classes are named in PascalCase
Non-public starts with a leading underscore
Name mangling