1.实例对象属性和实例方法
class Cat(object): def __init__(self,name): # 定义一个实例 属性 self.name = name # 定义了一个实例方法 def info(self): print(self.name) def show(self): print(‘Show Run :‘) self.info()
# 测试
# 创建一个实例对象
tom = Cat(‘Tom‘) # 使用实例属性 print(tom.name) # 使用实例方法 tom.info() tom.show() # Python中万物皆对象 Cat.show(tom) # 一般不这样用,一般都是用实例对象调用实例属性和方法
输出:
Tom
Tom
Show Run :
Tom
Show Run :
Tom
# 结论: # 为什么类名不能调用 实例 对象属性和实例对象方法呢? # 因为类对象存在时,不一定有实例对象存在 # 实例属性和实例方法只能由实例对象调用
2.类对象和类属性
class ClassRoom(object): # 当定义一个类属性时,相当于这个类中的全局变量 # 该类的所有对象都 可以使用该 类属性 # 可以在所有的对象间进行数据共享 center_kong_tiao = ‘格力空调‘ # 实例方法 def show(self): print(‘实例方法中去访问类属性:‘) print(ClassRoom.center_kong_tiao)
# 测试 cr901 = ClassRoom() print(cr901.center_kong_tiao) cr902 = ClassRoom() print(cr902.center_kong_tiao) cr901.center_kong_tiao = ‘海尔空调‘ print(cr901.center_kong_tiao) print(cr902.center_kong_tiao) ClassRoom.center_kong_tiao = ‘海尔空调‘ print(cr901.center_kong_tiao) print(cr902.center_kong_tiao)
# 输出: 格力空调 格力空调 海尔空调 格力空调 海尔空调 海尔空调
3.类方法
@classmethod def 方法名(cls,...): pass
Math.max(1,2)
class MyMath(object): # 定义一个类属性 n = 999 # 标准格式 @classmethod # 这是一个装饰 器,用来表示下面的方法是一个类方法 def sum(cls,*args): print(cls.n) m = 0 for i in args: m += i return m # @classmethod 是一个装饰 器,用来修饰一个方法成为类方法,当在执行该 类方法时,解释 会自动 将类对象传递到参数 cls中 @classmethod def show(cls): print(‘show class method‘)
# 执行类方法 print(MyMath.sum(1,2,3,4,5)) mm = MyMath() print(mm.sum(1, 2, 3, 4, 5)) MyMath.show()
输出: 999 15 999 15 show class method
4.静态方法
@staticmethod def 方法名(参数列表....): pass
class EncodeUtil(object): n = 1 # 编码方法 @staticmethod def encode_data(data, format): print(f‘对数据 {data} 使用 {format} 格式 进行了编码‘) # 解码方法 @staticmethod def decode_data(data, format): print(EncodeUtil.n) print(f‘对数据 {data} 使用 {format} 格式 进行了解编码‘) # 测试 eu = EncodeUtil() eu.encode_data(‘hello‘,‘utf-8‘) EncodeUtil.encode_data(‘Hello‘,‘utf-8‘) EncodeUtil.decode_data("hello",‘GBK‘)
输出: 对数据 hello 使用 utf-8 格式 进行了编码 对数据 Hello 使用 utf-8 格式 进行了编码 1 对数据 hello 使用 GBK 格式 进行了解编码
5.总结
原文:https://www.cnblogs.com/tanhuan-share/p/13086894.html