Python 私有属性

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 作者:Presley
# 邮箱:[email protected]
# 时间: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)

猜你喜欢

转载自www.cnblogs.com/Presley-lpc/p/9826283.html