Python 3: Some Material Adapted From Upenn Cis391 Slides and Other Sources
Python 3: Some Material Adapted From Upenn Cis391 Slides and Other Sources
somefile.className.method(abc)
somefile.myFunction(34)
from import *
from somefile import *
Everything in somefile.py gets imported
To refer to anything in the module, just use
its name. Everything in the module is now in
the current namespace.
Take care! Using this import command can
easily overwrite the definition of an existing
function or variable!
className.method(abc)
myFunction(34)
from import
from somefile import className
Only the item className in somefile.py gets
imported.
After importing className, you can just use
it without a module prefix. Its brought into the
current namespace.
Take care! Overwrites the definition of this
name if already defined in the current
namespace!
className.method(abc) imported
myFunction(34) Not
imported
Directories for module files
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
Creating and Deleting
Instances
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)
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.
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
Traditional Syntax for Access
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age
parentClass.__init__(self, x, y)
class student:
...
def __repr__(self):
return Im named + self.full_name
...
>>> f.__class__
< class studentClass at 010B4C6 >