Day14
1.class后面紧接着是类名,即Student,类名通常是大写开头的单词,紧接着是(object),表示该类是从哪个类继承下来的
class Student(object):
pass
tt = Student()
print(tt) #<__main__.Student object at 0x000002366AF8C9C8>
print(type(Student)) #<class 'type'>
tt.name = 'James'
print(tt.name) #James
2.__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。
class Student(object):
# __init__ 方法:
def __init__(self,name,score):
self.name = name
self.score = score
person1 = Student('Tom',100)
print(person1.name) # Tom
print(person1.score) # 100
# 数据封装
def thescore(mark):
print('%s:%s'%(mark.name,mark.score))
thescore(person1) # Tom:100
有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传,Python解释器自己会把实例变量传进去
3.get_name方法和set_score方法
class Student(object):
def __init__(self, name, gender):
self.name = name
self.__gender = gender
def get_gender(self):
return self.__gender
def set_gender(self,gender):
if gender == 'male' or gender == 'female':
self.__gender = gender
else:
raise ValueError('Bad gender')
# 测试:
bart = Student('Bart', 'female')
if bart.get_gender() != 'female':
print('测试失败!')
else:
bart.set_gender('male')
if bart.get_gender() != 'male':
print('测试失败!')
else:
print('测试成功!')
#测试成功
4.继承和多态
当我们定义一个class的时候,可以从某个现有的class继承,新的class称为子类(Subclass),而被继承的class称为基类、父类或超类(Base class、Super class)。
class Plant(object):
def still(self):
print('Plant is still.')
class Tree(Plant):
pass
class Grass(Plant):
pass
tree = Tree()
tree.still()
grass = Grass() # Plant is still.
grass.still() # Plant is still.
当子类和父类都存在相同的run()方法时,我们说,子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run()。
class Plant(object):
def still(self):
print('Plant is still.')
class Tree(Plant):
def still(self): # 子类与父类都有still()方法时,父类会被覆盖
print('Tree is still.')
class Grass(Plant):
def still(self):
print('Grass is still.')
tree = Tree()
tree.still()
grass = Grass() # Tree is still.
grass.still() # Grass is still.
print('\n')
# 多态
def still_twice(sth):
sth.still()
sth.still()
still_twice(Plant())
still_twice(Tree())
class Flower(Plant):
def still(self):
print('Flower is beautiful')
still_twice(Flower())
Tree is still.
Grass is still.
Plant is still.
Plant is still.
Tree is still.
Tree is still.
Flower is beautiful
Flower is beautiful
5.hasattr(),setattr(),getattr()
class Hi(object):
def __init__(self):
self.x = 9
def power(self):
return self.x*self.x
obj = Hi()
# hasattr(obj,'x') 判断这个对象是否有属性'x'
print(hasattr(obj,'x'),hasattr(obj,'y')) # True False
print(setattr(obj,'y',10)) # 添加一个属性'y'
print(hasattr(obj,'y')) # True
print(getattr(obj,'y')) # 10
print(obj.x) #获取属性'x' 9
getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404