Python 之 内置方法二 (Python 第十篇)

__dict

print('创建字符串:好好学习,天天向上')
strtest = 'good good study,day day up'


# 显示属性
# 方法属性和方法对象属性不同


class person:
    name = 'Yorlen'
    age = 23

    def __init__(self):
        self.name = 'none'
        self.age = 99

    @staticmethod
    def say():
        print('Hello!')
        pass


print('打印类Person的dict: \t', person.__dict__)
'''
类的内置函数和自定义方法及属性都放在类__dict__里面
对象中的__dict__中存储了一些初始化中的属性及属性值
但是 内置的数据类型 是没有__dict__的
如果存在继承关系,子父类有各自的__dict__
但是实例化之后,如果子类重写,那么__dict__都与子类一直
否则与父类一致。
'''
person1 = person()
print('打印person1的dict:\t', person1.__dict__)
dic = {'name': 'Yorlen'}
try:
    print('打印字典dic的dict:', dic.__dict__)
except AttributeError as reason:
    print('打印字典dic的dict错误原因:\t', reason)

# 返回当前范围内的变量、方法和定义的类型列表
# 带参数时,返回参数的属性、方法列表。
print('__dir____dir____dir____dir__:' + str(strtest.__dir__()))
print('在上面结果中我们会看到每个字段都是字符串的内置方法。')
'''
The base class of the class hierarchy.
这个方法在类的分级中属于基类
When called, it accepts no arguments and
当调用它时,它不接受参数
returns a new featureless instance that has 
并返回一个新的无特性的实例
no instance attributes and cannot be given any.
该实例没有实例属性,也不能被赋予任何实例属性。
'''

结果

创建字符串:好好学习,天天向上
打印类Person的dict: 	 {'__module__': '__main__', 
'name': 'Yorlen', 'age': 23,
 '__init__': <function person
 .__init__ at 0x0000000001E23040>, 'say': <staticmethod object at 
 0x0000000001E07A00>, '__dict__': <attribute '__dict__'
  of 'person' objects>, '__weakref__': <attribute '__weakref__' of
   'person' objects>, '__doc__': None}
打印person1的dict:	 {'name': 'none', 'age': 99}
打印字典dic的dict错误原因:	 'dict' object has no attribute '__dict__'

__dir____dir____dir____dir__:['__repr__', '__hash__', '__str__', 
'__getattribute__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__',
 '__ge__', '__iter__', '__mod__', '__rmod__', '__len__', '__getitem__',
  '__add__', '__mul__', '__rmul__', '__contains__', '__new__', 'encode',
   'replace', 'split', 'rsplit', 'join', 'capitalize', 'casefold', 'title', 'center',
    'count', 'expandtabs', 'find', 'partition', 'index', 'ljust', 'lower', 'lstrip',
     'rfind', 'rindex', 
   'rjust', 'rstrip', 'rpartition', 'splitlines', 'strip', 'swapcase', 'translate',
    'upper','startswith', 'endswith', 'isascii', 'islower', 'isupper', 'istitle',
     'isspace', 'isdecimal', 'isdigit', 'isnumeric', 'isalpha', 'isalnum',
      'isidentifier', 'isprintable', 'zfill', 'format', 'format_map', '__format__',
       'maketrans',  '__sizeof__', '__getnewargs__', '__doc__', '__setattr__',
       '__delattr__',  '__init__', '__reduce_ex__', '__reduce__',
        '__subclasshook__',  '__init_subclass__', '__dir__', '__class__']
在上面结果中我们会看到每个字段都是字符串的内置方法。

__eq

# eq = equals
# 作比较
strtest1 = 'good good study,day day up'
# 可变类型地址不同
l1 = [1, 2, 3, 4]
l2 = [1, 2, 3, 4]
print('字符串和列表同类之间的比较')
print('id(l1), id(l2)', id(l1), id(l2))
print('l1.__eq__(l2)', l1.__eq__(l2))
print('l1 == l2', l1 == l2)
print('l1 is l2', l1 is l2)
# 不可变类型地址相同
print('id(strtest1), id(strtest)', id(strtest1), id(strtest))
print('strtest1.__eq__(strtest)', strtest1.__eq__(strtest))
print('strtest1 == strtest', strtest1 == strtest)
print('strtest1 is strtest', strtest1 is strtest)

结果

字符串和列表同类之间的比较
id(l1), id(l2) 40636928 40623616
l1.__eq__(l2) True
l1 == l2 True
l1 is l2 False
id(strtest1), id(strtest) 31545264 31545264
strtest1.__eq__(strtest) True
strtest1 == strtest True
strtest1 is strtest True

__format

# format 格式化
# 当参数填空时,返回原字符串或者说是原对象
print('strtest.__format__(\'\')', strtest.__format__(''))


class people:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# 重写__format__方法
    def __format__(self, format_spec):
        if format_spec == '':
            return str(self)
        return "I'm " + self.name + ", " + str(self.age) + " years old!"


Jone = people('Jone', 18)
print('people.__format__(Jone, Jone)', people.__format__(Jone, Jone))
print('people.__format__(Jone, "")', people.__format__(Jone, ""))
print('Jone.__format__(Jone)', Jone.__format__(Jone))
print('Jone.__format__("")', Jone.__format__(""))
# self参数必须要填实参,如果是类名,会报警告
# 告诉你类型错误,请注意参数类型
# 这时候你就需要看看参数的参数有没有对了
# print(people.__format__(people,""))
# 这句话也可以运行,但是警告无参
print('people.__format__(people(\'Rose\', 16), " "', people.__format__(people('Rose', 16), " "))
# 这里1只是用作占位符,读者在第二个参数中写任何内容都可以
print('people.__format__(Jone, 1)', people.__format__(Jone, 1))

结果

strtest.__format__('') good good study,day day up
people.__format__(Jone, Jone) I'm Jone, 18 years old!
people.__format__(Jone, "") <__main__.people object at 0x0000000001E1A040>
Jone.__format__(Jone) I'm Jone, 18 years old!
Jone.__format__("") <__main__.people object at 0x0000000001E1A040>
people.__format__(people('Rose', 16), " " I'm Rose, 16 years old!
people.__format__(Jone, 1) I'm Jone, 18 years old!

转发评论收藏加关注呦
转发评论收藏加关注呦
转发评论收藏加关注呦
转发评论收藏加关注呦
转发评论收藏加关注呦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值