面向对象编程
1.面向对象编程
2.类和实例
3.访问限制
4.实例属性和类属性
1.面向对象
1.设计类
2.属性和方法
class Student(object):
#类内的叫方法,self指向创建的实例本身
#初始属性方法
def __init__(self,name,score):
self.name = name
self.score = score
#方法
def print_score(self):
print('%s:%s' % (self.name,self.score))
#实例化对象1
xiaohong = Student('xiaohong',98)
print(id(xiaohong))
#实例化对象2
xiaobai = Student('xiaobai',81)
print(id(xiaobai))
#实例化对象2
xiaobai = Student('xiaobai',81)
print(id(xiaobai))
#实例对象占用内存空间,而且每一个都有
print(xiaobai.name,xiaobai.score)
xiaobai.print_score()
xiaohong.print_score()
继承、封装、多态
封装
class Student(object):
#类内的叫方法,self指向创建的实例本身
def __init__(self,name,score):
self.name = name
self.score = score
def print_score(self):
print('%s:%s' % (self.name,self.score))
def get_grade(self):
if self.score >=90:
return 'A'
elif self.score >= 60:
return 'B'
else:
return 'C'
xiaolu = Student('xiaolu',87)
print(xiaolu.get_grade())
访问限制
class Student(object):
#类内的叫方法,self指向创建的实例本身
def __init__(self,name,score):
#加'__'表示属性私有
self.__name = name
self.__score = score
def print_score(self):
print('%s:%s' % (self.__name,self.__score))
def get_grade(self):
if self.__score >=90:
return 'A'
elif self.__score >= 60:
return 'B'
else:
return 'C'
def set_score(self,score):
if 0 <= score <=100:
self.__score = score
else:
raise ValueError('分数必须大于0小于100')
def get_score(self):
return self.__score
xiaolu = Student('xiaolu',87)
print(xiaolu.get_score())
print(xiaolu.set_score(80))
类属性
#实例属性,必须通过说出实话或者实例化对象,通过对象去访问
class Student(object):
def __init__(self,name,score):
self.__name = name
self.__score = score
#类属性,不需要实例化对象,直接通过类名访问,可以理解成公有的
class Student(object):
name = 'Student'
print(Student.name)
继承
class Animal(object):
def run(self):
print('Animal is running')
class Dog(Animal):
pass
class Cat(Animal):
pass
#
dog = Dog()
dog.run()
cat = Cat()
cat.run()
class Dog(Animal):
def run(self):#重写方法
#调用父类的方法
#super().run()
print('Dog is running')
def eat(self):
print('eat meat')
dog = Dog()
dog.run()
class Cat(Animal):
def run(self):#重写方法
#调用父类的方法
#super().run()
print('Dog is running')
def eat(self):
print('eat fish')
多态
#代码运行时才确定对象的类型
b = Animal() #b是Animal类型
c = Dog() #cs是Dog类型
#
# #判断对象是否属于该类
#
print(isinstance(b,Animal))
print(isinstance(c,Dog))
print(isinstance(c,Animal))
print(isinstance(b,Dog))
#调用run_twice方法,需要传递Animal类的对象或者Animal的子类
def run_twice(animal):
animal.run()
animal.run()
animal.eat()
run_twice(Dog())
run_twice(Cat())
run_twice(Animal())
类型判断type
import types
def fn():
pass
#判断是不是函数类型
print(type(fn)==types.FunctionType)
#判断是不是内部函数
print(type(abs)==types.BuiltinFunctionType)
#getattr(),setattr(),hasattr()
class MyObject(object):
def __init__(self):
self.x = 9
def power(self):
return self.x *self.x
obj=MyObject()
#obj 有属性x吗
print(hasattr(obj,'x'))
print(obj.x)
print(hasattr(obj,'y'))
#设置一个'y'的值
setattr(obj,'y',19)
print(hasattr(obj,'y'))
print(getattr(obj,'y'))
#dir()
print(obj.__dir__())
print(dir(obj))