Python 面向对象


一、面向对象技术简介

  • 方法
  • 类变量
  • 数据成员
  • 方法重写
  • 局部变量
  • 实例变量
  • 继承
  • 实例化
  • 对象

Python 中类提供了面向对象的所有基本功能:类的继承可以允许多个基类,派生类可以覆盖基类中的任何方法,方法中可以调用基类中的同名方法

对象可以包含任意数量和类型的数据



二、类对象

1.实例化

类对象支持两种操作:属性引用和实例化

class MyClass:
	i = 12345
	def f(self):
		return 'hello world'

# 实例化
x = MyClass()

# 属性引用、访问方法
print(x.i)
print(x.f())

输出结果:

12345
hello world

2.__init__()

类有一个名为 __init__() 方法,也就是类的构造方法

def __init__(self):
    self.data = []

该方法在类实例化时自动调用

x = MyClass()

当然,__init__() 可以有参数。

class Complex:
	def __init__(self, realpart, imagpart):
		self.r = realpart
		self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i)

输出结果:

3.0 -4.5

3.self代表类的实例、而非类

类方法和普通方法只有一个区别:类方法必须有一个额外的第一个参数名称,习惯性为 self

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

t = Test()
t.prt()

输出结果:

<__main__.Test object at 0x000001DB2F5DEE08>
<class '__main__.Test'>

从结果看,self 代表的是类的实例,代表当前对象的地址,而 self.class 则指向类。

self详细介绍



三、类方法

类方法使用 def 关键字定义,必须包含参数 self,且是第一个参数,self 代表类的实例。

class People:
    # 定义基本属性	
    name = ''	
    age = 0	
    
    # 定义私有属性	
    __weight = 0	
    
    # 定义构造方法	
    def __init__(self, n, a, w):		
        self.name = n		
        self.age = a		
        self.__weight = w	
    def speak(self):
        print("%s说:我 %s 岁" % (self.name, self.age))
        
p = People('王克', 10, 30)
p.speak()

输出结果:

王克说:我 10 岁

1.继承

子类(派生类)继承父类的属性和方法。

class 子类(父类):

父类还可以用表达式。

class 子类(modname.父类):

表示父类定义在另一个模块中。

实例

class People:
	def __init__(self, n, a, w):
		self.name = n			# 定义基本属性
		self.age = a
		self.__weight = w		# 定义私有属性
	def speak(self):
		print("%s说:我%s岁" % (self.name, self.age))

# 单继承示例
class Student(People):
	def __init__(self, n, a, w, g):
		People.__init__(self, n, a, w)	# 调用父类构造方法
		self.grade = g
	def speak(self):			# 覆写父类的方法
		print("%s说:我%s岁了,在读%s年级" % (self.name, self.age, self.grade))

s = Student("王小可", 10 ,60 ,3)
s.speak()

输出结果:

王小可说:我10岁了,在读3年级

2.多继承

多继承格式:

class 子类(父类1, 父类2, 父类3):

上面的子类,父类1,父类2,父类3如果包含相同的方法名,python从左到右查找

class People:
	def __init__(self, n, a, w):	# 定义构造方法
		self.name = n				# 类的属性
		self.age = a
		self.__weight = w			# 类的私有属性
	def speak(self):
		print("%s说:我%s岁。" % (self.name, self.age))

# 单继承示例
class Student(People):
	def __init__(self, n, a, w, g):
		People.__init__(self, n, a, w)	# 调用父类构造方法
		self.grade = g
	def speak(self):				# 覆写父类speak()方法
		print("%s说:我%s岁,在读%s年级。" % (self.name, self.age, self.grade))

class Speak():
	def __init__(self, n, t):
		self.name = n
		self.topic = t
	def speak(self):
		print("我叫%s,是一个演说家,演讲主题是%s" % (self.name, self.topic))

# 多重继承
class Sample(Speak, Student):
	def __init__(self, n, a, w, g, t):
		Speak.__init__(self, n, t)
		Student.__init__(self, n, a, w, g)

test = Sample('wangke', 10, 50, 5, 'python')
test.speak()

输出结果:

我叫wangke,是一个演说家,演讲主题是python

3.方法重写

如果父类方法不能满足需求,需要在子类重写父类的方法。

class Parent:  
	def myMethod(self):
		print('调用父类方法')


class Child(Parent):  
	def myMethod(self):
		print('调用子类方法')


c = Child()  
c.myMethod()	# 子类调用重写方法
super(Child, c).myMethod()	# 用子类对象调用父类已被覆盖的方法

super() 用于调用父类。

输出结果:

调用子类方法
调用父类方法


四、类属性与方法

1.类的私有属性

__private_attr两个下划线开头,声明类的私有属性。

私有属性不能在类的外部被使用和直接访问。在类内部的方法中访问时:self.__private


实例:

class JustCounter:
	__secretCount = 0		# 私有变量
	publicCount = 0			# 公开变量

	def count(self):
		self.__secretCount += 1
		self.publicCount += 1
		print(self.__secretCount)

counter = JustCounter()
counter.count()
counter.count()
print(counter.publicCount)
print(counter.__secretCount)	# 报错,实例不能访问私有变量

输出结果:

1
2
2
Traceback (most recent call last):
  File "C:/workspace/python/kirk/pycharm/LeetCode/test.py", line 14, in <module>
    print(counter.__secretCount)
AttributeError: 'JustCounter' object has no attribute '__secretCount'

2.类的私有方法

__private_method:两个下划线开头,声明私有方法。

私有方法只能在类的内部调用,不能在类的外部调用。self.__private_methods


实例:

class Site:
	def __init__(self, name, url):
		self.name = name	# public
		self.__url = url	# private

	def who(self):
		print(self.name)
		print(self.__url)

	def __foo(self):
		print('私有方法')

	def foo(self):
		print('公共方法')
		self.__foo()

x = Site('wangke', 'www.keye.com')
x.who()		# 正常输出
x.foo()		# 正常输出
x.__foo()	# 报错

输出结果:

wangke
www.keye.com
公共方法
私有方法
Traceback (most recent call last):
    x.__foo()	# 报错
AttributeError: 'Site' object has no attribute '__foo'

3.类的专有方法:

  • __init__:构造函数,生成对象时调用
  • __del__:析构函数,释放对象时调用
  • __repr__:打印,转换
  • __setitem__:按照索引赋值
  • __getitem__:按照索引获取值
  • __len__:获取长度
  • __cmp__:比较运算
  • __call__:函数调用
  • __add__:加运算
  • __sub__:减运算
  • __mul__:乘运算
  • __truediv__:除运算
  • __mod__:求余运算
  • __pow__:乘方
  • __str__:描述信息

4.运算符重载

Python支持运算符重载,可以对类的专有方法进行重载。

class Vector:
	def __init__(self, a, b):
		self.a = a
		self.b = b

	def __str__(self):
		return 'Vector (%d, %d)' % (self.a, self.b)

	def __add__(self, other):
		return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2, 10)
v2 = Vector(5, -2)
print(v1 + v2)

输出结果:

Vector(7,8)
原文地址:https://www.cnblogs.com/keye/p/15204542.html