一、类, 面向对象一个很重要的载体
1. 类的定义
class StuentName(object):
pass
2. 类里面一般都是由很多函数组成,函数的第一个参数默认都是self
如果需要全局变量,就在类的内部直接定义
3. 类的内部在调用函数或者调用变量的时候,必须使用self.变量 或者self.函数
self 代表的是类实例化以后的个体
4.类的实例化
实例化类的首字母小写作为实例,然后类实例化
studentName = StudentName();
5. 构造器
6. 继承
'''
class A(object):
name = "ajing"
def hello(self):
print("hello {0}".format(self.name))
def test(self):
self.hello()
print("This is test.")
a = A()
b = A()
2.类的构造器说明
类的构造器就是类在初始化的时候,首先,必须要执行的函数
举例:
class A(object):
#
def __init__(self, name):
self.name = name
print("init class A")
def hello(self):
print("hello {0}".format(self.name))
a = A("ajing")
a.hello()
3.继承 spuer用法
重写
调用: 先去找子类中的方法,如果子类中找不到对应的方法,就是父类中找
多继承:如果父类中都有该方法,那么先继承谁, 就用谁的方法。
案例一:
class Animal(object):
def __init__(self, name):
print("你现在正在初始化一个Animal")
def run(self):
print("Animal can run.")
class Bird(Animal):
def __init__(self):
print("bird")
def fly(self):
print("Bird can fly.")
class Cat(Animal):
def __init__(self, name, sex):
self.name = name
self.sex = sex
super(Cat, self).__init__(self.name)
print("我是一只猫,啦啦啦啦")
def jiao(self):
print("miao miao miao miao")
def run(self):
print("我是一只猫,会上树来会跑路.")
class BianYi(Cat, Bird):
pass
# animal = Animal()
# cat = Cat()
# cat.run()
# bianYi = BianYi()
cat = Cat("mao", "man")
执行效果:
补充知识点。
java 中的set和get方法
private host;
private port;
public getHost():
return host
public setHost(String host):
this.host = host
案例二:
import codecs class Student(object): def __init__(self, id, name, score): self.id = id self.name = name self.score = score class InitStduents(): def __init__(self): self.students = list() self.init() def init(self): self.students.append(Student(1001, "aaa", 59)) self.students.append(Student(1002, "bbb", 96)) self.students.append(Student(1003, "ccc", 87)) self.students.append(Student(1004, "ddd", 89)) self.students.append(Student(1005, "eee", 33)) self.students.append(Student(1006, "fff", 85)) self.students.append(Student(1007, "ggg", 78)) self.students.append(Student(1008, "hhh", 97)) self.students.append(Student(1009, "iii", 31)) self.students.append(Student(1010, "jjj", 93)) def sort(self): return sorted(self.students, key=lambda student: student.score) def writeFile(self, newStudents): with codecs.open("sortStudent.txt", "w")as f: for i in newStudents: f.write("id = {0}".format(i.id)) f.write("\t") f.write("name = {0}".format(i.name)) f.write("\t") f.write("score = {0}".format(i.score)) f.write("\n") def main(): students = InitStduents() newStudents = students.sort() students.writeFile(newStudents) if __name__ == "__main__": main()
执行效果:
案例三:阶乘
class JinCinCount(object): def __init__(self, n): self.n = n def jc(self, n): result = 1 if n == 0: return result else: for i in range(1, n+1): result *= i return result def count(self): count = 0 for i in range(0, int(self.n) + 1): count += self.jc(i) print("count = {0}".format(count)) def main(): n = input("Please inpurt a number: ") jinCinCount = JinCinCount(int(n)) jinCinCount.count() if __name__ == "__main__": main()
执行效果: