定义和使用类
下面展示一些
内联代码片
。
1.#声明类
成员函数(必须要有一个参数),参数代表实例(对象)自身,可以用这个参数引用类的属性和成员函数
#声明类
class Person: #例4-1:定义一个类
def SayHello(self):
'''
成员函数(必须要有一个参数),参数代表实例(对象)自身,
可以用这个参数引用类的属性和成员函数
'''
print("Hello!")
2.定义和使用对象的实例
# In[] :
class Person: #例4-2:定义和使用对象的实例
def SayHello(self):
print("Hello!")
p = Person() #定义对象的实例
p.SayHello() #引用对象的实例
代码运行结果:
Hello!
3.成员函数和成员变量
# In[] :
class MyString: #例4-3:
str = "MyString" #成员变量
def output(self):
print(self.str)
s = MyString()
s.output()
代码运行结果:
MyString
4.构造函数(对类进行初始化) #通过构造函数对类初始化 __XXX__表示系统定义的名字
# In[] :
class MyString: #例4-4:构造函数(对类进行初始化)
def __init__(self): #通过构造函数对类初始化 __XXX__表示系统定义的名字
self.str = "MyString"
def output(self):
print(self.str)
s = MyString()
s.output()
代码运行结果:
MyString
5.在类UserInfo中使用带参数的构造函数
# In[] :
class UserInfo: #例4-5: 在类UserInfo中使用带参数的构造函数
def __init__(self, name, pwd): #__XXX表示类中的私有变量名
self.username = name #公有变量useranme
self._pwd = pwd #私有变量_pwd
def output(self):
print("用户: "+self.username +"\n密码: "+ self._pwd)
u = UserInfo("admin", "123456")
u.output()
代码运行结果:
用户: admin
密码: 123456
6.析构函数
# In[] :
class MyString: #例4-6: 析构函数
def __init__(self): # 构造函数
self.str = "MyString"
def __del__(self): # 析构函数(xi 构函数)
print("beybey~")
def output(self):
print(self.str)
s = MyString()
s.output()
del s #删除对象
代码运行结果:
MyString
beybey~
静态变量
7.静态变量
# In[] :
#静态变量
class Users: #例4-7: 定义一个类User,使用静态变量online_conut记录当前在线的用户数量
online_count = 0 #静态变量
def __init__(self): #构造函数,创建对象时User.online_count加1
Users.online_count+=1
def __del__(self): #析构函数,释放对象时User.online_count减1
Users.online_count-=1
a = Users() #创建User对象
a.online_count +=1
print(Users.online_count)
代码运行结果:1
8.静态方法(只能使用类和对象调用静态方法)
# In[] :
class MyClass: #例4-8:静态方法(只能使用类和对象调用静态方法)
var1 = 'String 1' #静态变量
@staticmethod #静态方法
def staticmd(): #无参数
print("我是静态方法")
MyClass.staticmd()
c = MyClass()
c.staticmd()
代码运行结果:
我是静态方法
我是静态方法
9.定义类
# In[] :
class MyClass: #例4-9:定义类
val1 = 'String 1' #静态变量
def __init__(self): #构造函数
self.val2 = 'Value 2'
@classmethod #类方法
def classmd(cls):
print('类: ' + str(cls) + ', val1: '+ cls.val1 + ',无法访问val2的值')
MyClass.classmd()
c=MyClass()
c.classmd()
代码运行结果:
类: <class ‘main.MyClass’>, val1: String 1,无法访问val2的值
类: <class ‘main.MyClass’>, val1: String 1,无法访问val2的值
10.使用isinstance函数判断对象类型
# In[] :
class MyClass: #例4-10:使用isinstance函数判断对象类型
val1 = 'String 1'
def __init__(self):
self.val2 = 'Value 2'
c = MyClass()
print( isinstance(c, MyClass))
s = [1, 2, 3, 4]
print(isinstance(s, list))
代码运行结果:
True
True
类的继承和多态
11.类的继承和多态
class A:
def __init__(self, propertyA): #构造函数
self.propertyA = propertyA #类A的成员变量
def functionA(): #类A的成员函数
class B (A) : #B继承A的方法
propertyB #类B的成员变量
def functionB(): #类B的成员函数
objB = B() #定义一个类B的对象objB
print(objB.propertyA) #访问类A的成员变量
objB.functionA() #访问类A的成员函数
代码运行结果:
12.一个关于类继承的实例
# In[] :
import time #例4-11:一个关于类继承的实例
class Users:
usersanme = "" #成员变量
def __init__(self, uname): #成员函数
self.username = uname #公有变量
print('(构造函数:'+self.username+')')
#显示用户名
def dispUserName(self):
print(self.username)
class UserLogin(Users): #Users的子类
def __init__(self, uname, lastLoginTime): #成员函数
Users.__init__(self, uname) #调用父类Users的构造函数(用父类名字调用)
self.lastLoginTime = lastLoginTime
def dispLoginTime (self): #成员函数
print(" 登录时间为: "+ self.lastLoginTime)
#获取当前时间
now = time.strftime('%Y-%m%d %H:%M:%S',time.localtime(time.time()))
#声明3个对象
myUser_1 = UserLogin('admin', now) #首先,调用子类的成员函数,成员函数继承父类
myUser_2 = UserLogin('lee', now) #然后,用父类名字调用父类成员函数中的构造函数
myUser_3 = UserLogin('zhang', now)
#分别调用父类和子类的函数
myUser_1.dispUserName()
myUser_1.dispLoginTime()
myUser_2.dispUserName()
myUser_2.dispLoginTime()
myUser_3.dispUserName()
myUser_3.dispLoginTime()
代码运行结果:
(构造函数:admin)
(构造函数:lee)
(构造函数:zhang)
admin
登录时间为: 2020-0528 17:08:03
lee
登录时间为: 2020-0528 17:08:03
zhang
登录时间为: 2020-0528 17:08:03
13.#抽象类和多态(抽象方法不包含任何实现的代码,其函数体用pass;多态值抽象类中定义的一个方法,
# In[] :
from abc import ABCMeta, abstractmethod # 理4-12演示抽象类和多态
class Shape(object): #可以在其子类中重新实现,不同子类中的实现方法也不相同)
__metaclass__ = ABCMeta #定义抽象类
def __init__(self):
self.color = 'black' #默认使用黑色
@abstractmethod #定义抽象方法(抽象类是包含抽象方法的类,本身不实现任何方法)
def draw(self):pass
class circle(Shape): #继承父类Shape
def __init__(self, x, y, r): #定义圆心坐标和半径
self.x=x
self.y=y
self.r=r
def draw(self):
print("Draw circle: (%d, %d, %d)" %(self.x, self.y, self.r))
class line(Shape):
def __init__(self, x1, y1, x2, y2): #定义起止坐标值
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def draw(self):
print("Draw Line: (%d, %d, %d, %d)" %(self.x1, self.y1, self.x2, self.y2))
c= circle(10,10,5)
c.draw()
h = line(10,10,20,20)
h.draw()
代码运行结果:
Draw circle: (10, 10, 5)
Draw Line: (10, 10, 20, 20)
c= circle(10,10,5)
h = line(10,10,20,20)
list = []
list.append(c)
list.append(h)
for i in range(len(list)):
list[i].draw()
代码运行结果:
Draw circle: (10, 10, 5)
Draw Line: (10, 10, 20, 20)
复制对象
15.复制对象
#复制对象
mycircle = circle(20, 20, 5) #复制对象
newcircle = mycircle
newcircle.draw()
代码运行结果:
Draw circle: (20, 20, 5)
16.通过参数复制对象
def drawCircle(c): #通过参数复制对象
if isinstance(c, circle): #这个函数判断变量c是否是类circle的实例
c.draw()
c1 = circle(100,100,15)
drawCircle(c1)
代码运行结果:
Draw circle: (100, 100, 15)
def drawShape(s): #例4-16
if isinstance(s, Shape):
s.draw()
c1 = circle(100,100,15) #画圆
drawShape(c1)
h = line(10,10,20,20) #画直线
drawShape(h)
代码运行结果:
Draw circle: (100, 100, 15)
Draw Line: (10, 10, 20, 20)