python 面向对象笔记

Python 面向对象小结,最近在学习Python,在学习到面向对象时有些记不住,特写此笔记:
1.定义类
    class People:
        num = 0
        def SayHello(self):
            print("Hello");
2.定义对象
    P = People()
    p.SayHello()
3.构造函数__init__()
    class People:
        def __init__(self,a,b):
            self.name = name
            self.age = age
    x = People('lily',25)
    print("姓名:",x.name,"年龄:",x.age)
4.析构函数
    class People:
        def __init__(self,a,b):
            self.name = name
            self.age = age
        def __def__(self):
            print("no")
    x = People('lily',25)
    del x
释放对象资源
5.实例属性和类属性
实例属性:在__init__中定义的属性,定义时以self开头,通过对象名访问
类属性:在类中方法之外定义的属性,可以通过类名访问,也可以通过对象名访问
    class People:
        def __init__(self,a,b):
            self.name = name //实例属性
            self.age = age
            People.num = 1  //类属性
        def PrintName(self):
            print("姓名:",self.name,"年龄:",self.age)
        def Num(self):
            print("人数:",People.num)
    p1 = People('lily',25)
    p1.PrintName()
    p1.Num()

6.私有成员和公有成员(Python不存在真正意义上的私有成员)
私有成员:以__开头的属性为私有属性,在类的成员方法内访问
    class People:
        def __init__(self,a,b,w):
            self.name = name //实例属性
            self.age = age
            self.__weigth = w //私有属性
            People.num += 1  //类属性

    P1 = People('lilya',23,50)
    print(P1.name)
    print(P1._People__weigth) //访问私有属性

7.方法
私有方法:以“__”开头,在对象方法中用self调用
静态方法:可以通过类名和对象名调用,但不能直接访问属于对象的成员,只能访问类成员
    class People:
        def __init__(self,a,b,w):
            self.name = name //实例属性
            self.age = age
            self.__weigth = w //私有属性
            People.num += 1  //类属性
        def __outputWeigth(self):
            print("体重:",self.__weigth) //访问私有属性
        def PrintName(self):
            print("姓名:",self.name,"年龄:",self.age)
            self.__outputWeigth //调用私有方法
        def Num(self):
            print("人数:",People.num) //
        @ staticmethod
        def getNum():
            return People,num

    P1 = People('lilya',23,50)
    
    print(P1.name)
    print(P1._People__weigth) //访问私有属性

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值