# python 类中的默认属性 # /usr/sbin/py/python # -*-coding:utf8-*- import abc class Animal(metaclass=abc.ABCMeta): @abc.abstractmethod def run(self): pass class Cat(Animal): def __init__(self, name, age): self.name = name self.age = age def run(self): print("%s is running" % self.name) def __str__(self): return "类似于java中的重写toString方法:name:%s age:%s" % (self.name, self.age) def __repr__(self): return "repr方法执行" c1 = Cat("tom", 12) print(c1) # 如何改变c1的输出方式 重写 str 和 repr方法 # print 执行的就是 对象下的str方法,如果对象中找不到str就会去找repr作为替代的返回结果 # 通过 format 定制输出 class Date: df1 = ":" df2 = "-" _format_dict = { df1: "{0.year}:{0.month}:{0.day}", df2: "{0.year}-{0.month}-{0.day}" } def __init__(self, year, month, day): self.year = year self.month = month self.day = day def __format__(self, format_spec): if not format_spec: fm = self._format_dict[self.df2] else: fm = self._format_dict[format_spec] return fm.format(self) d1 = Date("2020", "03", "08") print(d1.__format__(d1.df2)) print(format(d1, d1.df1)) print(format(d1)) # __slots__ 目的是为了节省内存 有__slots__ 则__dict__不存在 class Person: 'doc注释' __slots__ = ["name","age"] p1 = Person() p2 = Person() # print(p1.__dict__) 报错 p1.name = "jake" print(p1.name) # p1.hobby = "sing" 使用了__slots__就不能通过这种方式赋值 print(p1.__doc__) print(p1.__module__) # 模块名 print(p1.__class__) # 类名
来源:CSDN
作者:XiaoqiangNan
链接:https://blog.csdn.net/XiaoqiangNan/article/details/104759191