面向对象编程需要使用类,类和实例息息相关,有了类之后我们必须创建一个实例,这样才能调用类的方法。首先看一下类的结构模式:
class<类名>:
<语句>
- 类的私有属性:__private_attrs 两个下划线开头,声明该属性为私有,不能在类地外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs
- 类的方法:在类地内部,使用def关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数self,且为第一个参数
类的专有方法:
__init__ 构造函数,在生成对象时调用
__del__ 析构函数,释放对象时使用
__repr__ 打印,转换
__setitem__ 按照索引赋值
__getitem__ 按照索引获取值
__len__ 获得长度
__cmp__ 比较运算
__call__ 函数调用
__add__ 加运算
__sub__ 减运算
__mul__ 乘运算
__div__ 除运算
__mod__ 求余运算
__pow__ 称方
首先看一下构建类的构成及实例化:
In [1]: # -*- coding: utf-8 -*-
...: """
...: Created on Sun Jan 21 00:31:07 2018
...: 类的定义构建
...: @author: BruceWong
...: """
...:#构建person的类
...: class person():
...: name = '' #首先定义一下变量
...: age = 0
...: __weight = 0
...: def __init__(self,name,age,weight): #初始化变量
...: self.name = name #重新给类的name变量赋值,并可以全局调用
...: self.age = age
...: self.__weight = weight
...: def infoma(self): #定义speak函数
...: print('%s is %s weights %s'%(self.name,self.age,self.__weight))
...: person = person('bruce',25,60) #将变量赋值给person类实例化
...: print(person)
...: infoma = person.infoma() 调用person类的infoma函数方法
...:
<__main__.person object at 0x0000020F23172780>
bruce is 25 weights 60
其次通过使用类的内置方法进行方法的构造:
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 21 00:31:07 2018
类的定义构建
@author: BruceWong
"""
class person():
def __init__(self,name,age,weight):
self.name = name
self.age = age
self.__weight = weight
def __cmp__(self):
pow_age = self.age.__pow__(2)
print(pow_age)
def __len__(self):
name_del = self.name.__len__()
print(name_del)
def __add__(self):
adds = self.age.__add__(self.__weight)
print(adds)
def infoma(self):
print('%s is %s weights %s'%(self.name,self.age,self.__weight))
print(person.__class__)
print(person.__repr__)
person = person('bruce',25,60)
print(person)
infoma = person.infoma()
cmp = person.__cmp__()
lens = person.__len__()
adds = person.__add__()
print('doc is %s'%person.__doc__)
print('dir is %s'%person.__dir__)
print('delatter is %s'%person.__delattr__)
print('gt is %s'%person.__gt__)
print('hash is %s'%person.__hash__)
print('init is %s'%person.__init__)
print('new is %s'%person.__new__)
'''
output:
<class 'type'>
<slot wrapper '__repr__' of 'object' objects>
<__main__.person object at 0x0000020744E69668>
bruce is 25 weights 60
625
5
85
doc is None
dir is <built-in method __dir__ of person object at 0x0000020744E69668>
delatter is <method-wrapper '__delattr__' of person object at 0x0000020744E69668>
gt is <method-wrapper '__gt__' of person object at 0x0000020744E69668>
hash is <method-wrapper '__hash__' of person object at 0x0000020744E69668>
init is <bound method person.__init__ of <__main__.person object at 0x0000020744E69668>>
new is <built-in method __new__ of type object at 0x00000000617BDFD0>
'''