# 类里的6种方法:实例方法、类方法、静态方法、魔法方法、自由方法、私有方法
class test(object):
__new = "无法在外部访问"
_new = "类对象和子类可以访问"
new = "类变量 外部可访问"
# 魔法方法
def __init__(self):
self.num = 10
self._num = 20
self.__num = 30
# 自由方法
def freedom(): # 参数中没有self 或 cls,也没有任何装饰器
print('该方法是自由方法')
# print(new) # 会报错,因为此自由方法未定义变量new
print(test.new) # 访问类变量的方法同静态方法,通过类名访问
# 双下划线私有方法,外部不能访问
def __hello():
print('该方法外部访问不到')
# 单划线私有方法,类对象和子类可以访问
def _singleHello():
print('该方法类和子类可访问')
# 静态方法
@staticmethod
def static_method():
print("这是静态方法:", test.new)
# 类方法
@classmethod
def class_method(cls):
print("这是类方法:", cls.new)
# 实例方法
def hi(self):
print("这是实例方法:",self.new)
t = test()
t.hi()
test.freedom()
test.class_method()
test.static_method()
test._singleHello()
# test.__hello() # 私有方法不能访问