Python 面向对象
In [1]:
class Student(object):
pass
bart = Student()
bart.name = 'gaufung'
bart.name
Out[1]:
将强制性的属性作为类和对象的构造函数参数,__int__(self)
In [2]:
class Student(object):
def __init__(self,name):
self.name = name
bart = Student('zhang san')
bart.name
Out[2]:
In [5]:
class Student(object):
def __init__(self,name):
self.__name = name
def get_name(self):
return self.__name
bart = Student('gaofeng')
bart.__name
In [6]:
bart.get_name()
Out[6]:
因为 Python
解释器将 __name
解释为 _Student__name
属性
In [7]:
bart._Student__name
Out[7]:
所以当选择将__name
进行修改赋值的时候,相当于动态给bart
对象动态添加了__name
属性。
In [9]:
bart.__name='lisi'
bart.get_name()
Out[9]:
In [16]:
class Animal(object):
def run(self):
print 'Animal is running'
class Dog(Animal):
def run(self):
print 'Dog is running'
class Cat(Animal):
def run(self):
print 'Cat is running'
def competition(animal):
animal.run()
competition(Animal())
competition(Dog())
competition(Cat())
In [17]:
class Chair(object):
def run(self):
print 'The chair will not run'
competition(Chair())
In [18]:
type(123)
Out[18]:
In [19]:
type('abc')
Out[19]:
In [20]:
type(None)
Out[20]:
In [21]:
# 查看函数
type(abs)
Out[21]:
In [22]:
# 查看自定义对象
a = Animal()
type(a)
Out[22]:
In [23]:
b = Cat()
c = Dog()
isinstance(b,Animal)
Out[23]:
In [25]:
isinstance(b,Dog)
Out[25]:
In [26]:
# 能使用type的地方都可以改成isinstance
isinstance(123,int)
Out[26]:
In [27]:
isinstance('gau',str)
Out[27]:
In [29]:
class MyObject(object):
def __init__(self):
self.x = 9
def power(self):
return self.x**2
obj = MyObject()
hasattr(obj,'x')
Out[29]:
In [30]:
hasattr(obj,'y')
Out[30]:
In [31]:
setattr(obj,'y',19)
hasattr(obj,'y')
Out[31]:
In [32]:
getattr(obj,'y')
Out[32]:
In [34]:
class Student(object):
name = 'student'
s = Student()
# 因为 s 没有 name 属性,因此向class方向查找
s.name
Out[34]:
In [36]:
Student.name
Out[36]:
In [37]:
s.name = 'gaufung'
s.name
Out[37]:
In [38]:
Student.name
Out[38]:
In [42]:
class Student(object):
pass
def set_age(self,age):
self.age = age
from types import MethodType
s1 = Student()
s1.set_age = MethodType(set_age,s1)
s1.set_age(25)
s1.age
Out[42]:
In [43]:
# 但是对一个对象动态绑定一个方法,对另一个对象并不起作用
s2 = Student()
s2.set_age(12)
可以对整个类动态绑定一个方法
In [45]:
def set_score(self,score):
self.score = score
Student.set_score = set_score
s1 = Student()
s2 = Student()
s1.set_score(100)
s1.score
Out[45]:
In [46]:
s2.set_score(99)
s2.score
Out[46]:
In [47]:
class Student(object):
__slots__=('name','age')
s = Student()
s.name = 'gaufung'
s.age = 25
In [48]:
s.grade = 'A'
In [51]:
# 对于继承类并不起作用
class GraduateStudent(Student):
pass
g = GraduateStudent()
g.grade = 'B'
g.grade
Out[51]:
In [52]:
class Student(object):
def __init__(self,name):
self.name = name
def __str__(self):
return "Student's name is {}".format(self.name)
__repr__=__str__
Student('gaofeng')
Out[52]:
In [54]:
print Student('gaufung')
In [59]:
class Fib(object):
def __init__(self):
self.a, self.b = 0, 1 # 初始化两个计数器a,b
def __iter__(self):
return self # 实例本身就是迭代对象,故返回自己
def next(self):
self.a, self.b = self.b, self.a + self.b # 计算下一个值
if self.a > 100000: # 退出循环的条件
raise StopIteration()
return self.a # 返回下一个值
for i in Fib():
print i,
In [64]:
class Fib(object):
def __getitem__(self,n):
a,b=1,1
for i in range(n):
a,b=b,a+b
return a
Fib()[4]
Out[64]:
In [65]:
class MyClass(object):
def __init__(self):
self.age = 10
def __getattr__(self,attr):
if attr == 'score':
return 'A'
obj = MyClass()
obj.age
Out[65]:
In [66]:
obj.score
Out[66]:
类似新浪微博web API的链式生成方式
In [67]:
class Chain(object):
def __init__(self,path=''):
self._path = path
def __getattr__(self,path):
return Chain('%s/%s'%(self._path,path))
def __str__(self):
return self._path
chain = Chain()
print chain.gau.fung.liu.bei
In [68]:
class Student(object):
def __init__(self):
self.name = 'gaufung'
def __call__(self):
print 'Student name is {}'.format(self.name)
s = Student()
s()
In [69]:
JAN = 1
FEB = 2
MAR = 3
更好的方法是为这样的枚举类型定义一个class类型,然后,每个常量都是class的一个唯一实例。Python提供了Enum类来实现这个功能:
In [70]:
from enum import Enum
Week = Enum('Week',('Mon','Tue','Wed','Thu','FRI','SAT','SUN'))
for name,member in Week.__members__.items():
print name,'=>',member,',',member.value
精确控制枚举类型,使用类
In [71]:
from enum import Enum,unique
@unique
class Week(Enum):
Mon = 0
Tue = 1
Wed = 2
Thu = 3
Fri = 4
Sat = 5
Sun = 6
day1 = Week.Mon
print(day1)
In [73]:
day1.value
Out[73]:
In [ ]: