python写一个类_python3学习笔记--002--写一个类

代码:

[laolang@localhost classtest]$ cat test.py

#!/usr/bin/env python

class person:

def __init__(self,name,age,sex):

self.name = name

self.age = age

self.sex = sex

def sayHello(self,msg='Hello'):

print(msg)

def printInfo(self):

print('name:' + self.name + ' age:' + str(self.age) + ' sex:' + self.sex )

class student(person):

def __init__(self,name,age,sex,id,score):

person.__init__(self,name,age,sex)

self.id = id

self.score = score

def sayHi(self,msg='Hi'):

print(msg)

def printInfo(self):

person.printInfo(self)

print('id:' + str(self.id) + ' score:' + str(self.score))

per = person('person',24,'man')

per.sayHello()

per.printInfo()

stu = student('xiaodaima',24,'man',1001,100)

stu.sayHi()

stu.sayHello()

stu.printInfo()

[laolang@localhost classtest]$ 运行效果:

[laolang@localhost classtest]$ ./test.py

Hello

name:person age:24 sex:man

Hi

Hello

name:xiaodaima age:24 sex:man

id:1001 score:100

[laolang@localhost classtest]$

定义一个类:

class className:

def __init__(self,arg1,arg2,...):

pass

def method1(self,arg1,aarg2,...):

pass

def method2(self,arg1,aarg2,...):

pass className为类名

__init__(self,arg1,arg2,...)是类的构造方法,当我们使用per = person('person',24,'man')的时候,就会调用person类中的__init__方法

在类中,如果要调用自身的属性,则应当使用self.propertyName

继承一个类:

class className(superClassName):

def __init__(self,arg1,arg2,arg3,...):

superClassName.__init__(self,arg1,arg2)

self.arg3 = arg3

def method1(self)

superClassName.method1(self)

... 在类名后的括号中写上父类的名字

调用父类的方法:superClassName.method(self,arg1,arg2,..)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值