- 类
- 类方法、属性
- 类方法、属性私有化
- 类的继承
定义类:
class name(): pass
类实例化后,可以使用其属性,实际上,创建一个类之后,可以通过类名访问其属性,如果直接使用类名修改其属性,那么将直接影响到已经实例化的对象。
>>> class test(): x = 1>>> one = test() >>> one.x 1 >>> one.x = 2 >>> one.x 2
类属性私有化,两个下划线开头声明属性为私有__name
>>> class test(): __x =1 x = __x +1 >>> z = test >>> z.x 2 >>> z.__x ...... AttributeError: type object 'test' has no attribute '__x'
类的方法
在类地内部,使用def关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数self,且为第一个参数
>>> class classes(): def run(self):print('hello python!') def __run(self):print('hello __python!') >>> cla = classes() >>> cla.run() hello python!
私有化的类方法:
两个下划线开头,声明该方法为私有方法__name(self),不能在类地外部调用
>>> class hehe(): def __a(self):print('aaa') def a(self):self.__a() >>> x = hehe() >>> x.a() aaa >>> x.__a() ...... AttributeError: 'hehe' object has no attribute '__a'
类的专有方法:
| __init__ | 构造函数 |
| __del__ | 析构函数 |
| __repr__ | 打印,转换 |
| __setitem__ | 按照索引赋值 |
| __getitem__ | 按照索引获取值 |
| __len__ | 获得长度 |
| __cmp__ | 比较运算 |
| __call__ | 函数调用 |
| __add__ | 加 |
| __sub__ | 减 |
| __mul__ | 乘 |
| __div__ | 除 |
| __mod__ | 求余 |
| __pow__ | 乘方 |
>>> class player: def __init__(self,name,age,pay): self.name = name self.age = age self.pay = pay def display(self): print("%s is %s years old, and he earn %s a year" %(self.name,self.age,self.pay)) >>> kobe = player('kobe',35,'1000000') >>> kobe.display() kobe is 35 years old, and he earn 1000000 a year
类的继承
>>> class super_class(): #建立父类 def run(self): print('this is super class') >>> class this_class(super_class): #建立子类继承父类,单继承 def run_(self): self.run() #调用父类方法 >>> a = this_class() >>> a.run() this is super class >>> a.run_() this is super class
例子:
>>> class FirstClass(): #建立一个超类 def __init__(self,value): self.data = value def run(self): print("First Class :",self.data) >>> class SecondClass(FirstClass): #建立一个子类继承超类FirstClass def __init__(self,value): self.data = value def __add__(self,other): #建立一个类的私有加方法__add__ return SecondClass(self.data + other) def run(self): #复写run方法 print("SecondClass :",self.data) def __str__(self,other): #__str__方法:字符串的方式获取对象的内容、类型、数值属性等信息 return '[SecondClass:%s]' %self.data def mul(self,other): self.data *= other >>> a = SecondClass('okk') #创建一个类实例对象 >>> a.run() SecondClass : okk >>> print(a) [SecondClass:okk] >>> b = a + 'hehehe' #调用到__add__方法 >>> print(b) [SecondClass:okkhehehe] >>> b.run() SecondClass : okkhehehe >>> a.mul(5) >>> print(a) [SecondClass:okkokkokkokkokk]
浙公网安备 33010602011771号