zoukankan      html  css  js  c++  java
  • Python 私有属性

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # 作者:Presley
    # 邮箱:1209989516@qq.com
    # 时间:2018-08-05
    # 类的方法
    class Animal:
        def __init__(self,name):
            self.name = name
            self.__num = None
        count = 10
        hobbie = "wohaoshuai"
    
        @classmethod #将下面方法变成只能通过类方式去调用而不能通过实例方式去调用。因此调用方法为:Animal.talk(). !!!!类方法,不能调用实例变量
        def talk(self):
            print("{0} is talking...".format(self.hobbie))#因为hobbie为类变量所以可以通过类方式或者实例方式,若括号中为self.name实例变量则只能通过Animal.talk()方式调用
    
        @staticmethod #当加上静态方法后,此方法中就无法访问实例变量和类变量了,相当于把类当作工具箱,和类没有太大关系
        def walk():
            print("%s is walking...")
    
        @property #属性,当加了property后habit就变成一个属性了就不再是一个方法了,调用时不用再加()
        def habit(self): #习惯
            print("%s habit is xxoo" %(self.name))
    
        @property
        def total_players(self):
            return  self.__num
    
        @total_players.setter
        def total_players(self,num):
            self.__num = num
            print("total players:",self.__num)
    
        @total_players.deleter
        def total_players(self):
            print("total player got deleted.")
            del self.num
    #@classmethod
    # Animal.hobbie
    # Animal.talk()
    # d = Animal("wohaoshuai")
    # d.talk()
    
    
    # @staticmethod
    # d = Animal("wohaoshuai2")
    # d.walk()
    
    # @property
    d = Animal("wohaoshuai3")
    # d.habit
    print(d.total_players)
    d.total_players = 2
    
    #del d.total_players
    d.__num = 9#相当于在外面设置了一个属性__num,和实例中的__num没有任何瓜葛。
    #print("OUT:%s" %(d.__num))#报错,提示没有__num属性
    #如果非要访问,可用以下方法
    print("OUT:%s" %(d._Animal__num))
    
    print(d.total_players)
  • 相关阅读:
    chrome/edge 自签名证书造成浏览器无法访问
    linux 下 取进程占用内存(MEM)最高的前10个进程
    总结记录一下我对YZ数据中台指标相关平台的理解感悟与思考
    史上最全之微信群发拼手气红包测试用例
    vue使用filterBy,orderBy实现搜索筛选功能
    前端处理防抖和节流
    箭头函数()=>{}与function的区别
    html不用任何控件上传文件
    Java必备知识--线程池
    Java必备知识--日志框架
  • 原文地址:https://www.cnblogs.com/Presley-lpc/p/9826283.html
Copyright © 2011-2022 走看看