今天在网上看了篇文件,关于类的定制,原来类也能那么风骚的使用啊,涨了不少知识,一时半会还没消化呢,先把自己的练习代码贴上,后面慢慢吃透。
__author__ = 'lulongfei'
class Student(object):
def __init__(self, name):
self.name = name
print Student('Michael')
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name: %s)'% self.name
# print Student('Michael')
s = Student('Michael')
print (s)
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name :%s)'%self.name
__repr__ = __str__
s = Student('Michael')
s
class Fib(object):
def __init__(self):
self.a, self.b = 0, 1
def __iter__(self):
return self
def next(self):
self.a, self.b = self.b, self.a + self.b
if self.a > 1000:
raise StopIteration()
return self.a
for n in Fib():
print n
class Fib(object):
def __getitem__(self, n):
if isinstance(n, int):
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
if isinstance(n, slice):
start = n.start
stop = n.stop
a, b = 1, 1
L = []
for x in range(stop):
if x >= start:
L.appent(a)
a, b = b, a + b
return L
class Student(object):
def __init__(self):
self.name = 'Michael'
def __getattr__(self, attr):
if attr == 'score':
return 99
s = Student()
print s.name
print s.score
class Student(object):
def __getattr__(self, attr):
if attr == 'age':
return lambda : 25
a = Student()
print a.age()
class Student(object):
def __getattr__(self, attr):
if attr == 'age':
return lambda :25
raise AttributeError('\'Student\' object has no attribute\'%s\''% attr)
s = Student()
s.name
class Student(object):
def __init__(self, name):
self.name = name
def __call__(self):
print 'My name is %s.'%self.name
s = Student('Michael')
s()
callable(Student())
print callable(max)