0
点赞
收藏
分享

微信扫一扫

Python编程:class类面向对象



通常在单独的文件中定义一个类


创建类

class Employee(object):
"""所有员工的基类"""
empCount = 0 # 类变量

def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print("Total Employee %d" % Employee.empCount)

def displayEmployee(self):
print("Name: %s Salary: %d" % (self.name, self.salary))

# 创建 Employee 类的对象
employeeA = Employee("Tom", 2000)
employeeB = Employee("Jack", 2500)
employeeC = Employee("Jimi", 3000)

# 访问数据成员

# 访问类变量
print(Employee.empCount) # 使用类名称访问类变量 3

# 访问实例变量
# 添加,删除,修改类的属性
employeeA.age = 23 # 添加
employeeA.age = 24 # 修改
del employeeA.age # 删除

setattr(employeeB, "age", 25) # 设置属性,不存在则新建
print(hasattr(employeeB, "age")) # 检查属性存在 True
print(getattr(employeeB,"age")) # 访问对象属性 25
delattr(employeeB, "age") # 删除属性


# 访问对象方法
employeeA.displayCount() # Total Employee 3
employeeA.displayEmployee() # Name: Tom Salary: 2000
employeeB.displayEmployee() # Name: Jack Salary: 2500
employeeC.displayEmployee() # Name: Jimi Salary: 3000

# 内置类属性
print(Employee.__doc__) # 打印类文档 所有员工的基类
print(Employee.__name__) # 类名 Employee
print(Employee.__module__) # 类定义所在的模块 __main__
print(Employee.__base__) # tuple 类的所有父类<class 'object'>
print(Employee.__dict__) # dict 类的属性(由类的数据属性组成)
"""
{
'__dict__': <attribute '__dict__' of 'Employee' objects>,
'__init__': <function Employee.__init__ at 0x0000000001263A60>,
'__weakref__': <attribute '__weakref__' of 'Employee' objects>,
'__module__': '__main__',
'__doc__': '所有员工的基类',
'empCount': 3,
'displayCount': <function Employee.displayCount at 0x0000000001263AE8>,
'displayEmployee': <function Employee.displayEmployee at 0x0000000001263E18>
}
"""

self代表类的实例,而非类

class Test(object):
def prt(self):
print(self)
print(self.__class__)

t1 = Test()
t2 = Test()
t1.prt()
"""
<__main__.Test object at 0x000000000120C550>
<class '__main__.Test'>
"""

t2.prt()
"""
<__main__.Test object at 0x000000000120C518>
<class '__main__.Test'>
"""
print("="*50)

对象销毁

引用计数器,循环垃圾收集器

class Point(object):
def __init__(self, x , y): # 构造函数
self.x = x
self.y = y

def __del__(self): # 析构函数
class_name = self.__class__.__name__
print(class_name, "销毁")


p1 = Point(1, 4)
p2 = p1
p3 = p1
print(id(p1), id(p2), id(p3)) # 打印对象的id
# 18991312 18991312 18991312
del p1
del p2
del p3
# Point 销毁
print("="*50)

类的继承

面向对象的编程好处之一是代码重用

在python中继承中的一些特点:

1. 在继承中基类的构造(init()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。

2. 在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。

区别在于类中调用普通函数时并不需要带上self参数

3. Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,

它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。

如果在继承元组中列了一个以上的类,那么它就被称作”多重继承” 。

# 父类
class Parent(object):
parent_attr = 10
def __init__(self):
print("Parent init")

def parent_method(self):
print("parent_method")

def method(self):
print("method of parent")

def set_attr(self, attr):
Parent.parent_attr = attr

def get_attr(self):
return Parent.parent_attr

# 子类
class Child(Parent):
def __init__(self):
print("Child init")

def child_method(self):
print("Child_method")

def method(self): # 重写父类方法
print("method of child")

child = Child() # 实例化子类 Child init
child.child_method() # 调用子类的方法 Child_method
child.parent_method() # 调用父类方法 parent_method
child.method() # 子类调用重写方法 method of child
child.set_attr(20) # 设置属性值
print(child.get_attr()) # 获取属性值 20

# 判断A是B的子类
print(issubclass(Child, Parent)) # True

# 判断A是B的实例
print(isinstance(child, Child)) # True

重载方法

class Student(object):
def __init__(self, name, age): # 构造函数
self.name = name
self.age = age

def __del__(self): # 析构方法, 删除一个对象del调用
print("del")

def __str__(self): # 用于将值转化为适于人阅读的形式 str(obj)
return "name:"+self.name+";age:"+str(self.age)

__repr__ = __str__ # 转化为供解释器读取的形式

def __cmp__(self,student): #对象比较,用于排序 py3中删除
if self.age > student.age:
return 1
elif self.age < student.age:
return -1
else:
return 0

def __add__(self, student): # 运算符重载+
return Student(self.name,self.age+student.age)

student1 = Student("Tom", 23)
student2 = Student("Jack", 25)
student3 = Student("Jimi", 24)

print(repr(student1)) # name:Tom;age:23
print(str(student1)) # name:Tom;age:23
print(student1) # name:Tom;age:23

print(student1+student2) # name:Tom;age:48

类中数据的可访问性

class Counter(object):
public_count = 0 # 类公有变量
__private_count = 0 # 类私有变量

def count(self):
self.public_count += 1 # 实例公有变量
self.__private_count += 1 # 实例私有变量
print(self.__private_count)


counter = Counter() # 实例化
counter.count() # 1
counter.count() # 2
print(counter.public_count) # 访问实例公有变量 2
# print(counter.__private_count) # 访问实例私有变量 报错
print(counter._Counter__private_count) # 访问实例私有变量 2

print(Counter.public_count) # 访问类公有变量 0
# print(Counter.__private_count) # 访问类私有变量 访问出错

"""
单下划线:protected,本身和子类
双下划线:private,本身
头尾双下划线:系统定义特殊方法
"""


参考文章《Python 面向对象》
​​​http://www.runoob.com/python/python-object.html​​​




举报

相关推荐

0 条评论