1类的构成 类(Class) 由3个部分构成 类的名称:类名 类的属性:一组数据 类的方法:允许对进行操作的方法 (行为) 2定义类 class 类名: 方法列表 class Student(object): def run(self): print('学生跑步'
<1>类的构成
类(Class) 由3个部分构成
类的名称:类名
类的属性:一组数据
类的方法:允许对进行操作的方法 (行为)
<2>定义类
class 类名:
方法列表
class Student(object):
def run(self):
print('学生跑步')
def sing(self):
print('学生唱歌')
<3>创建对象
对象名 =类名() stu =Student()
Student类拥有的属性数据
stu.name ='gxj' stu.num ='123' stu.run() stu.sing() print(stu.name) print(stu.num)
<4>init()方法
class Student(object):
def __init__(self):
self.name ='gxj'
self.num ='123'
def run(self):
print('学生在跑步')
stu =Student()
print('学生的姓名:%s'%stu.name)
print('学生的座位号:%s'%stu.num)
结果如下: 学生的姓名:gxj 学生的座位号:123
init_方法传递参数
class Student(object):
def __init__(self,newName,newNum):
self.name =newName
self.num =newNum
def run(self):
print('学生在跑步')
stu =Student('gxj1','1234')
print('学生的姓名:%s'%stu.name)
print('学生的座位号:%s'%stu.num)
init_方法总结
__init__()方法,在创建一个对象时默认被调用,不需要手动调用 __init__(self)中,默认有1个参数名字为self,如果在创建对象时传递了2个实参,那么__init__(self)中出了self作为第一个形参外还需要2个形参,例如__init__(self,x,y) __init__(self)中的self参数,不需要开发者传递,python解释器会自动把当前的对象引用传递进去
<5>定义__str__()方法
当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据
class Student(object):
def __init__(self,newName,newAge):
self.name =newName
self.age =newAge
def __str__(self):
msg ='我是的姓名:'+self.name+'年龄:'+self.age
return msg
def run(self):
print('跑步')
stu =Student('gxj','17')
print(stu)
结果如下: 我是的姓名:gxj年龄:17
<6>self的用法
所谓的self,可以理解为自己
某个对象调用其方法时,python解释器会把这个对象作为第一个参数传递给self,所以开发者只需要传递后面的参数即可
class Animal(object):
def __init__(self,name):
self.name =name
def printName(self):
print('名字为:%s'%self.name)
def myPrint(anamil):
anamil.printName()
dog1 =Animal('东东')
myPrint(dog1)
dog2 =Animal('西西')
myPrint(dog2)
<7>保护对象的属性
<1>对象名.属性名 = 数据 ---->直接修改
<2>对象名.方法名() ---->间接修改
为了更好的保存属性安全,即不能随意修改,一般的处理方式为
<1>将属性定义为私有属性
<2>添加一个可以调用的方法,供调用
class Student1(object):
def __init__(self,name):
self.__name =name
def getName(self):
return self.__name
def setName(self,newName):
if len(newName)>=3:
self.__name =newName
else:
print('error:名字长度需要大于3或等于3')
xiaogao =Student1('xiaogao')
xiaogao.setName('xiaoniu')
print(xiaogao.getName())
xiaogao.setName('xiaosong')
print(xiaogao.getName())
总结: Python中没有像C++中public和private这些关键字来区别公 有属性和私有属性 它是以属性命名方式来区分,如果在属性名前面加了2个下划线'__',则 表明该属性是私有属性,否则为公有属性(方法也是一样,方法名前面加了2个下划线的话表示该 法是私有的,否则为公有的)。
