面向对象编程
掌握类的定义和使用
掌握类的私有成员和共有成员的定义和使用
掌握数据成员的定义和使用
掌握使用方法来描述对象所具有的行为
掌握属性的定义和使用
掌握类的封装以及类之间的继承、多态
了解类的专有方法
一:面向对象概述
1.类的定义使用
class MyClass(object):
i=123
def f(self):
ruturn"hello world"
use_class=MyClass()
print('调用类的属性:',use_class.i)
print('调用类的方法:',use_class.f())
2.类的方法
#类定义
class people:
#定义基本属性
name="
age=0
#定义私有属性,私有属性在类的外部无法直接访问
_weight=0
#定义构造方法
def_init_(self,n,a,w):
self.game=n
self.age=a
self._weight=w
def speak(self):
print("%s说 我%d岁。"%(self.name,self.age))
#实例化类
p=people('runoob',10,30)
p.speak()
二:深入介绍类
1.类的构造方法(构造函数和访问权限控制)
在类中_init_()称为构造函数
def_init_(self,n,a,w)'
self.name=n
self.age=a
self._weight=w
init()方法可以有参数
class Complex:
def_init_(self,realpart,imafpart)
self.r=realpart
self.i=imafpart
x=complex(3.0,-4.5)
print(x.r,x.i)
self代表类的参数而非类,类的方法与普通函数只有一个特殊的区别——他们必须有额外的一个参数,self
class DefaultInit(object):
def_init_(self,param):
print('带参数,参数值为',param)
def_init_(self):
print('不带参数')
DefaultInit()
print('实例化结束')
不带参数
注:一个类中最好只定义一个构造方法
2.类的访问权限
在类外我们可以通过非构造方法调用构造方法中的变量的属性所以我们需要学会控制类的访问权限
class Student(object):
def_init_(self,name,score):
self.name=name
self.score=score
bart=student('zth',80)
print(bart.score)
bart.score=80
print(bart.score)
80
80
(1)私有变量
class Student:
def_init_(self,name,score)
self._name=name
self._score=score
def get_information(self):
print("学生%s的分数为:%s"%(self._name,self._score))
person=Student("xiaoming","95")
person.get_information()
person.score=0
print('修改后的属性名:',person._score)
get_information()
xiaoming的分数为:95
修改后的属性名:0
学生xiaoming的分数为:95
(2)在类的外部获取私有变量
实例名_类名_变量名
(3)从外部修改私有变量的值
可在类内增加方法专门用于修改变量的值
(4)类的私有方法
私有方法:两个下划线开头
私有方法调用方式:self.方法名
class Student:
def_init_(self):
pass
def_func(self):
print("这是私有方法")
def_func(self):
print("现在为公有方法,接下类调用私有方法")
self.func()
student=Student()
print("通过调用公有方法来间接调用私有方法")
student.fun()