定义与使用类
类的定义
class testClass:
name = "Xu Huan"
def welcome(self):
print("Xu Huan is handsome")
xu = testClass()
print(xu.name)
xu.welcome()
Xu Huan
Xu Huan is handsome
Python要求类的方法的第一个参数必须是self,表示的是实例本身。
class testClass:
name = "Xu Huan"
def welcome(self):
print("实例:",self)
print("类:",self.__class__)
xu = testClass()
print(xu.name)
xu.welcome()
Xu Huan
实例: <__main__.testClass object at 0x0000015D2B529208>
类: <class '__main__.testClass'>
self是推荐写法,写成别的也可以。
class testClass:
name = "Xu Huan"
def welcome(this):
print("实例:",this)
print("类:",this.__class__)
xu = testClass()
print(xu.name)
xu.welcome()
Xu Huan
实例: <__main__.testClass object at 0x0000015D2B529D68>
类: <class '__main__.testClass'>
类的构造方法和析构方法
构造方法:实例化类时自动执行的方法,定义时用__init__
形式。
析构方法:销毁类时自动执行的方法,定义时用__del__
形式。
class MacketMember:
def __init__(self):
print("welcome")
def __del__(self):
pass
m = MacketMember()
welcome
类的私有属性
类的私有属性,对象无法调用,只有类内部才可以使用。
class MarketMember:
__count = 0
__name = ''
def __init__(self,name,count):
self.__count += count
self.__name = name
def seek(self):
print(self.__name + "积分为" + str(self.__count))
m = MarketMember('Xu Huan',300)
m.seek()
print(m.__count) #无法输出私有属性__count
Xu Huan积分为300
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-11-6e059803e4af> in <module>()
10 m = MarketMember('Xu Huan',300)
11 m.seek()
---> 12 print(m.__count) #无法输出私有属性__count
AttributeError: 'MarketMember' object has no attribute '__count'
类的私有方法
类的私有方法和私有属性一样,也是以双下划线__开始,不能被对象调用。
class MarketMember:
def __change(self,count):
print("修改后的分数是" + str(count))
m = MarketMember()
m.__change(500)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-13-caf5b4253243> in <module>()
4
5 m = MarketMember()
----> 6 m.__change(500)
AttributeError: 'MarketMember' object has no attribute '__change'
一个完整的类
class MarketMember:
__name = ""
count = 600
def __init__(self,name):
self.__name = name
print(self.__name + '当前积分:' + str(self.count))
def change(self,count1):
self.count += count1
print(self.__name + '更改后的积分为:' + str(self.count))
m = MarketMember('Xu Huan')
m.change(500)
print(m.count)
Xu Huan当前积分:600
Xu Huan更改后的积分为:1100
1100
类与类的关系
单继承
class MarketMember:
__name = "" #私有属性无法被继承的类使用
count = 600
def __init__(self,name):
self.__name = name
print(self.__name + '当前积分:' + str(self.count))
def change(self,count1):
self.count += count1
print(self.__name + '更改后的积分为:' + str(self.count))
class MyMember(MarketMember):
age = 0
def seekAge(self):
print("年龄为:" + str(self.age) + ",积分为:" + str(self.count))
m = MyMember('Xu Huan')
m.change(500)
m.age = 25
m.seekAge()
Xu Huan当前积分:600
Xu Huan更改后的积分为:1100
年龄为:25,积分为:1100
多继承
class Animals:
color = ""
weight = 0
def jump(self):
print('i can jump')
class cat:
def miaomiao(self):
print('i can miaomiao')
class whitecat(Animals,cat):
def white(self):
print('i am white')
w = whitecat()
w.jump()
w.miaomiao()
w.white()
i can jump
i can miaomiao
i am white
类的关联和依赖
依赖
Person类的方法gobyboat需要boat作为参数传入,这样才能调用boat的过河(overriver)方法,这就叫依赖。
class Person:
def gobyboat(self,boat):
boat.overriver()
class Boat:
def overriver(self):
print("go successfully!")
b = Boat()
p = Person()
p.gobyboat(b)
go successfully!
关联
class empluee:
id = 0
name = ''
class Company:
def __init__(self):
self.employee = employee()
重写
Python允许子类重写父类中已有的方法,而且不需要特殊的关键字进行说明。
class Animals:
color = ""
weight = 0
def jump(self):
print('i can jump')
class cat:
def miaomiao(self):
print('i can miaomiao')
class whitecat(Animals,cat):
def miaomiao(self):
print('i can white miaomiao')
def white(self):
print('i am white')
w = whitecat()
w.jump()
w.miaomiao()
w.white()
i can jump
i can white miaomiao
i am white
魔术方法
魔术方法能够给类增加魔力,如果对我们的对象实现(重载)了这些方法中的某一个,那么这个方法就会在特殊的情况下被Python自动调用。
#__call__方法是允许一个类的实例像函数一样被调用。
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def __call__(self,*args):
print(str(args[0] + args[1]))
p = Person('Xu Huan',22)
p(150,250)
400
#__getitem__、__setitem__是获取键或设置键,一般用于类中的一些自定义数据结构。
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
self._registry = {
'name' : name,
'age' : age
}
def __getitem__(self,key):
if key not in self._registry.keys():
raise Exception('please registry the key: %s first!' % (key,))
return self._registry[key]
def __setitem__(self,key,value):
if key not in self._registry.keys():
raise Exception('please registry the key: %s first!' % (key,))
self._registry[key] = value
p = Person('Xu Huan',22)
print(p['name'],p['age'])
p['age'] = 23
print(p['age'])
Xu Huan 22
23
#__get__、__set__,如果类的某个属性设置了描述符,对这个类的访问会触发特定的绑定行为。
class Meter:
def __init__(self,value = 0.0):
self.value = float(value)
def __get__(self,instance,owner):
return self.value
def __set__(self,instance,value):
self.value = float(value)
class Foot:
def __get__(self,instance,owner):
return instance.meter * 3.2808
def __set__(self,instance,value):
instance.meter = float(value) / 3.2808
class Distance:
meter = Meter()
foot = Foot()
d = Distance()
print(d.meter,d.foot)
d.meter = 1
print(d.meter,d.foot)
d.meter = 2
print(d.meter,d.foot)
0.0 0.0
1.0 3.2808
2.0 6.5616