class Province:
# 静态字段(类变量/属性)
country = '中国'
def __init__(self, name):
# 普通字段(实例变量/属性)
self.name = name
# 直接访问普通字段
obj = Province('河北省')
print obj.name
# 直接访问静态字段
Province.country
复制代码
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
self.__num = None #私有化变量,不允许外部访问
hobbie = 'meat'
@classmethod #类方法,不能访问实例变量
def talk(self):
print('is hobbie %s'%self.hobbie)
@staticmethod #静态方法,不能访问类变量和实例变量
def walk(self):
print('is walk %s'%self.hobbie)
@property #把方法变为属性
def habit(self):
print("%s habit is " %self.name)
@property
def total_player(self):
return self.__num
@total_player.setter # 修改属性
def total_player(self,num):
self.__num = num
print("total num:%s"%self.__num)
@total_player.deleter # 删除
def total_player(self):
print("total player got deleted")
del self.__num
d = Animal("anonymous")
print(d.total_player)
d.total_player = 3 #直接穿变量
d.__num = 9
print("Out:",d.__num)
print("to access private variable:",d._Animal__num)
# del d.total_player
print("Inside:",d.total_player)
#广度优先 先从左向右找同级别,再找上一级 新式类 class name(object)
#深度优先,先找左面第一个,如果没有,找上级然后在返回同级找。旧式类 class name
class A(object):
n = 'A'
def f1(self):
print("from A")
class B(A):
n = 'B'
def f1(self):
print('from B')
class C(A):
n = 'C'
def f1(self):
print("from C")
class D(B,C):
pass
p = D()
p.f1()