Python初学8-对象

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值