python 23 类中的默认属性

# 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__) # 类名
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值