1 staticmethod
在类里面把某个函数定义为静态函数,这样对该函数的调用不需要实例化后才能访问,也可以通过 类名.静态函数(args)来调用,比如
class Person:
@staticmethod
def static_method():
print("static_method called")
Person.static_method()
2 str()
用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式。比如
class Person:
def __str__(self):
return "hello"
print( str( {"name": "sysnap", "age": 21} ) )
print( str(p1) )
3 eval()
表达式求值,比如
def amazing(z):
'''This is the amazing.Helloworld'''
print("hello amazing", z)
def dump_func(func):
print("The function named: ", func.__name__)
print("The function docstring is: n", func.__doc__)
eval(func.__name__)("test")
dump_func( amazing )
4 super()
调用父类的函数,语法是
class C(B): def method(self, arg): super(C, self).method(arg)
比如
class Animal(object):
def __init__(self):
print("a的构造方法")
self.a = "动物"
def hello(self, name):
print("hello ", name)
class Cat(Animal):
def __init__(self):
print("b的构造方法")
self.b = "mao"
super(Cat, self).__init__()
def hello(self):
super(Cat, self).hello("cat")
c1 = Cat()
c1.hello()
5 iter()
迭代器用起来很灵巧,你可以迭代不是序列但表现处序列行为的对象,例如字典的键、一个文件的行,等等
i = iter('abcd')
print i.next()
print i.next()
print i.next()
s = {'one':1,'two':2,'three':3}
print s
m = iter(s)
print m.next()
print m.next()
print m.next()
with open('mydata.txt') as fp:
for line in iter(fp.readline, ''):
process_line(line)
6