1、基础对象(包括函数和变量)
【注】:self相当于java中的this指针,指向类中的变量参数
class People():
name=''
age = 0
def fun1(self):
print(str(self.age)+"岁"+self.name+'做了一件事')
people = People()
people.name='Tom'
people.age=10
people.fun1()
2、构造函数:def __init__(self)(类实例化时调用)
class P1():
name='p1初始化'
age=0
def __init__(self,name,age):
self.name = name
self.age = age
print(str(self.age)+"岁"+self.name+'P1构造函数调用')
print(P1.name+"-"+self.name+"-"+self.__class__.name)
#return 1 不可以有返回值
def fun1(self):
print(str(self.age)+"岁"+self.name+'调用p1函数fun1')
p1 = P1('name_p1',10)
p1.fun1()
print("---"+p1.name)
#a = p1.__init__()
#print(a,type(a))#构造函数返回为空
3、__dict__字典(获取类中所有变量参数)
class P2():
a = 1
b = 2
c = 3
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def fun1(self):
print('fun1')
def fun2(self):
print('fun2')
p2 = P2(3,4,5)
print(p2.__dict__)
4、类方法
【注】@classmethod @staticmethod
class P3():
sum = 0
def __init__(self):
print("构造函数里的"+str(self.sum))
@classmethod
def do_sum(cls):
cls.sum+=1
print("sum累加"+str(cls.sum))
@staticmethod
def static_sum():
print("static方法"+str(sum))
p3_1 = P3()
p3_1.do_sum()
p3_1.static_sum()
p3_2 = P3()
p3_2.static_sum()
p3_2.do_sum()
p3_3 = P3()
p3_3.static_sum()
p3_3.do_sum()
5、继承
可以使用
1>.父类. 调用父类变量或函数
2>.super(本类). 调用父类变量或函数
class Man():
name=''
age = 0
def __init__(self,age,name):
self.age=age
self.name=name
def fun1(self):
print("Man中"+str(self.age)+"岁"+self.name+'做了一件事')
people = People()
people.name='Tom'
people.age=10
people.fun1()
class Student(Man):
sex = '男'
age = 0
score = 0
def __init__(self,name,age,sex,score):
#Man.__init__(self, age, name)
super(Student,self).__init__(age,name)#调用父类
self.age=age
self.score=score
self.sex=sex
def fun1(self):
print("student中"+str(self.age)+"岁"+self.name+'做了一件事')
student = Student('Tom',15,'男',100)
print(student.name)
student.fun1()