类的定制

今天在网上看了篇文件,关于类的定制,原来类也能那么风骚的使用啊,涨了不少知识,一时半会还没消化呢,先把自己的练习代码贴上,后面慢慢吃透。


__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)



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值