Notes for Python's function# Defining a class class class_name: [statement 1] [statement 2]

Because it is a seperate program, a function doesn't see any of the variables that are in your main program(Functions run completely independent of the main program.), and your main program doesn't see any of the variables that are in a function.

<pre>def function_name(parameter_1,parameter_2):
    {this is the code in the function}
    {more code}
    {more code}
    return {value (e.g. text or number) to return to the main program}
 
 
 

 {this code isn't in the function} 

{because it isn't indented}
#remember to put a colon ":" at the end

#of the line that starts with 'def'

In short:

The only thing functions see of the main program is the parameters that are passed to it
the only thing the main program seens of functions is the returned value that it passes back

Reference:  http://www.sthurlow.com/python/lesson05/

Creating a Class

# Defining a class
class class_name:
    [statement 1]
    [statement 2]
    [statement 3]
    [etc]
here is an example, that creates the definition of a  Shape :

#An example of a class
class Shape:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    description = "This shape has not been described yet"
    author = "Nobody has claimed to make this shape yet"
    def area(self):
        return self.x * self.y
    def perimeter(self):
        return 2 * self.x + 2 * self.y
    def describe(self,text):
        self.description = text
    def authorName(self,text):
        self.author = text
    def scaleSize(self,scale):
        self.x = self.x * scale
    self.y = self.y * scale

The function called __init__ is run when we create an instance of Shape. self is how we refer to things in the class from within itself. self is the first parameter in any function defined inside a class.Any function or variable created on the first level of indentation (that is, lines of code that start one TAB to the right of where we put class Shape is automatically put into self. To access these functions and variables elsewhere inside the class, their name must be preceeded with self and a full-stop (e.g. self.variable_name). The self means these functions can be called and the variables can be accessible in other 

place inside the class.

Using a class

rectangle = Shape(100,45)
The __init__ function really comes into play at this time. We create an  instance  of a class by first giving its name (in this case,  Shape ) and then, in brackets, the values to pass to the __init__ function. The init function runs (using the parameters you gave it in brackets) and then spits out an  instance  of that class, which in this case is assigned to the name  rectangle .


#finding the area of your rectangle:
print rectangle.area()

#finding the perimeter of your rectangle:
print rectangle.perimeter()

#describing the rectangle
rectangle.describe("A wide rectangle, more than twice\
 as wide as it is tall")

#making the rectangle 50% smaller
rectangle.scaleSize(0.5)

#re-printing the new area of the rectangle
print rectangle.area()

Explanation for above code: our class instance, rectangle, as a self-contained collection of variables and functions. In the same way that we used self to access functions and variables of the class instance from within itself, we use the name that we assigned to it now (rectangle) to access functions and variables of the class instance from outside of itself. 


= opreator has different meaning for class and common variables:

Thinking back, when you say that one variable equals another, e.g. variable2 = variable1, the variable on the left-hand side of the equal-sign takes on the value of the variable on the right. With class instances, this happens a little differently - the name on the left becomes the class instance on the right.So in instance2 = instance1,instance2 is 'pointing' to instance1 - there are two names given to the one class instance, and you can access the class instance via either name.

Reference: http://www.sthurlow.com/python/lesson08/


Modules

"how do I get my classes to many places, in many programs?". The answer is to put them into a module, to be imported into other programs.
A module is a python file that (generally) has only defenitions of variables, functions, and classes. 

As you see, a module looks pretty much like your normal python program.

So what do we do with a module? We import bits of it (or all of it) into other programs.

To import all the variables, functions and classes from moduletest.py into another program you are writing, we use the import operator.


Pickles


Pickles, in Python, are objects saved to a file. An object in this case could be a variables, instance of a class, or a list, dictionary, or tuple. Other things can also be pickled, but with limits. The object can then be restored, or unpickled, later on. In other words, you are 'saving' your objects.

So how do we pickle? With the dump() function, which is inside the pickle module - so at the beginning of your program you will have to write import pickle. Simple enough? Then open an empty file, and use pickle.dump()to drop the object into that file.


# import the pickle module
import pickle

# lets create something to be pickled
# How about a list?
picklelist = ['one',2,'three','four',5,'can you count?']

# now create a file
# replace filename with the file you want to create
file = open('filename', 'w')

# now let's pickle picklelist
pickle.dump(picklelist,file)

# close the file, and your pickling is complete
file.close()

Now to re-open, or unpickle, your file. to use this, we would use  pickle.load() :

# import the pickle module
import pickle

# now open a file for reading
# replace filename with the path to the file you created in pickletest.py
unpicklefile = open('filename', 'r')

# now load the list that we pickled into a new object
unpickledlist = pickle.load(unpicklefile)

# close the file, just for safety
unpicklefile.close()

# Try out using the list
for item in unpickledlist:
    print item


Read lines of a file:

f = open('workfile', 'r')
for line in f:
	print line,





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值