类的成员,类的特殊方法

类的成员:

  在类中的私有字段和私有方法是不能被类意外的方法调用的。只能在类的内使用。

  在普通字段和方法前加两个下划线就可以把普通字段定义成私有字段或方法。

  在子类中,不能执行父类中的方法,不能获得父类的字段。示例:

class bar():
    def __init__(self):
        self.name = 'bar_name'
        self.__age = 18

    def get_age(self):
        return (self.__age)

class b(bar):
    def __init__(self):
        self.__b_age = 17
        super(b,self).__init__()


    def show(self):
        print ('class bar name is {}'.format(self.name))
        print ('__b_age is {}'.format(self.__b_age))
        # print ('__age is {}'.format(self.__age))
        self.bar__age = super(b,self).get_age()
        print (self.bar__age)

obj = b()
obj.show()
# class bar name is bar_name
# __b_age is 17
# 18

类中的特殊成员

class bar():
    def __init__(self):
        print ('bar __init__ month!')
    def __call__(self, *args, **kwargs):
        print ('__call__ month')
    def __int__(self):
        # default int number.
        return 1
    def __str__(self):
        return 'string value'

obj = bar()
obj()
int(obj)
# str(obj)
print (obj)
# bar __init__ month!
# __call__ month
# string value

obj = bar() 执行 __init__ 方法

obj() 执行 __call__ 方法

int(obj) 执行 __init__ 方法

print (obj) 执行 __str__ 方法

 类中比较重要的内部方法:

__getitem__  -> obj['test']

__setitem__ -> obj[213] = 98

__delitem__ -> del obj['test_key']

class bar():
    def __init__(self):
        print ('bar __init__ month!')
    def __getitem__(self, item):
        return ('getitem index value is: {}'.format(item))
    def __setitem__(self, key, value):
        # default int number.
        print ('{} = {}'.format(key,value))
    def __delitem__(self, key):
        print ('is delitem values: {}'.format(key))

obj = bar()
print (obj['test'])
obj[213] = 98
del obj['test_key']
# bar __init__ month!
# getitem index value is: test
# 213 = 98
# is delitem values: test_key

 25day类成员方法切片

test

原文地址:https://www.cnblogs.com/qikang/p/8698559.html