类和对象
1.class 类名:
类里面的内容
class cl1:
pass
实例化一个类
a=cl1(0)
2.构造函数(构造方法)
self:在类中的方法必须加上self参数
构造函数的实际意义:初始化
init(self,参数)
class cl2:
def __init__(self):
print("I am cl2 self!")
给类加上参数:给构造方法加上参数
class cl3:
def __init__(self,name,job):
print("My name is "+name+" My job is "+job)
属性:类里面的变量:self.属性名
class cl4:
def __init__(self,name,job):
self.myname=name
self.myjob=job
c=cl4("cxy","python")
print(c.myname)
方法:类里面的函数:def 方法名(self,参数)
class cl5:
def myfunc1(self,name):
print("hello!"+name)
c=cl5()
c.myfunc1("cxy")
class cl6:
def __init__(self,name,job):
self.myname=name
def myfunc1(self,name):
print("hello!"+self.myname)
c=cl6()
c.myfunc1("cxy")
3.继承与重载
继承(单继承,多继承)
父亲类(基类)
class father():
def speak(self):
print("I can speak!")
class mother():
def write(self):
print("I can write")
单继承:class 子类(父类)
class son (father):
pass
多继承:class 子类(父类……)
class daughter(father,mother):
def listen(self):
print("I can listen")
d=daughter()
d.speak()
重写(重载)
class son2(father):
def speak(self):
print("I can speak2!")
网友评论