# -*- coding: utf-8 -*-
'''
__doc__ 表示类的描述信息
__module__ 表示当前操作的对象在那个模块
__class__ 表示当前操作的对象的类是什么
__del__ 析构方法
__call__ 对象后面加括号,触发执行。
__dict__ 类或对象中的所有成员
__str__ 输出该方法的返回值。
__new__() 方法是在类准备将自身实例化时调用
类的普通字段属于对象;类中的静态字段和方法等属于类,
'''
class Foo():
#静态字段
country = '中国'
def __init__(self):
self.name = 'eric'
self.__age = 20 #这种样式的属于私有属性,只有在本类中才可以调用,外部和子类调用均会报错
def func(self):
print('eat eat eat')
#类方法
@classmethod
def class_func(cls): #必须传一个cls参数
print('类方法'.center(40,'+'))
#静态方法
@staticmethod
def show():
print('show')
def __call__(self, *args, **kwargs):
print('__call__')
def __del__(self):
print('我释放了')
#返回值
def __str__(self):
return '陈旭飞'
f = Foo() #执行init方法
print(Foo.__doc__)
print(f.__module__) #表示当前操作的对象在那个模块
print(f.__class__) # 表示当前操作的对象的类是什么
f() #执行__call__方法
# 获取类的成员,即:静态字段、方法、
print (Foo.__dict__)
#获得对象的成员 不包括静态字段
print(f.__dict__)
print(f) #输出 对象 会调用__str__
print(''.center(80,'-'))
'''
__getitem__、__setitem__、__delitem__
用于索引操作,如字典。以上分别表示获取、设置、删除数据
python3 之后不存在了
__getslice__、__setslice__、__delslice__
该三个方法用于分片操作,如:列表
'''
class city():
def __getitem__(self, item):
print('__getitem__',item)
def __setitem__(self, key, value):
print('__setitem__',key,value)
def __delitem__(self, key):
print('__delitem__',key)
c = city()
c['a'] #自动执行 __getitem__
c['k'] = '123' #自动执行 __setitem__
del c['a'] #自动执行 __delitem__
print(''.center(80,'-'))
class Bed(object):
def __init__(self,arg):
self.arg = arg
def __iter__(self): #用于迭代器
return iter(self.arg)
b = Bed([11,22,33])
for i in b:
print(i)
class Base(object):
def __init__(self):
print('Base __init__')
class Child(Base):
def __init__(self):
print('Child __init__')
#__new__() 方法是在类准备将自身实例化时调用
def __new__(cls, *args, **kwargs):
print('__new__')
return object.__new__(Base,*args, **kwargs)
child = Child()
print(type(child)) # <class '__main__.Base'>
python面向对象之系统函数
最新推荐文章于 2024-07-31 08:25:31 发布