代码:
[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,..)