Python3的对象和类

Python3的对象和类

使用class定义类
class Person():

pass  #pass表示这是个空类


class Person():
def __init__(self,name):
 self.name = name
hunter = Person('Elmer Fudd')
print(hunter.name)

继承,覆盖,添加新方法


# _*_ coding: utf-8_*_
class Car():
	def exclaim(self):
		print("I'm a Car! ")
class Yugo(Car):   #继承父类
	def exclaim(self): #覆盖
		print("I'm a Yugo!")
	def need_a_push(self): #添加新方法
		print("A little help here?")
give_me_a_car = Car()
give_me_a_yugo = Yugo()
give_me_a_car.exclaim()
give_me_a_yugo.exclaim()
give_me_a_yugo.need_a_push()

D:\MyPython>python test2.py
I'm a Car!
I'm a Yugo!
A little help here?

使用super 从父类得到帮助
class Person():
	def __init__(self, name):
		self.name = name
class EmailPerson(Person):
	def __init__(self, name, email):
		super().__init__(name) #通过super()方法获取了父类Person的定义
		self.email = email
bob = EmailPerson('Bob Frapples', '[email protected]')
print(bob.name)
print(bob.email)
D:\MyPython>python test2.py
Bob Frapples
[email protected]


使用属性(property)对特性(attribute)进行访问和设置

# _*_ coding: utf-8_*_
class Duck():
	def __init__(self, input_name):
		self.hidden_name = input_name
	def get_name(self):
		print('inside the getter')
		return self.hidden_name
	def set_name(self, input_name):
		print('inside the setter')
		self.hidden_name = input_name
	name = property(get_name, set_name)
fowl = Duck('Howard')
print(fowl.name)	#当访问name特性时,get_name()会被自动调用
fowl.get_name()		#显示调用
fowl.name = 'Daffy'	#当对name特性执行赋值操作时,set_name()方法会被调用
fowl.set_name('Daffy')
D:\MyPython>python test2.py
inside the getter
Howard
inside the getter
inside the setter
inside the setter

还可以使用定义属性的方式:装饰器

@property,用于指示getter方法

@name.setter,用于指示setter方法

# _*_ coding: utf-8_*_
class Duck():
	def __init__(self, input_name):
		self.hidden_name = input_name
	@property
	def name(self):
		print('inside the getter')
		return self.hidden_name
	@name.setter
	def name(self, input_name):
		print('inside the setter')
		self.hidden_name = input_name
	
fowl = Duck('Howard')
print(fowl.name)	
fowl.name = 'Daffy'	
print(fowl.name)


D:\MyPython>python test2.py
inside the getter
Howard
inside the setter
inside the getter
Daffy
除了使用name属性指向类中存储的某一特性,还可以指向一个计算结果值

# _*_ coding: utf-8_*_
class Circle():
	def __init__(self, radius):
			self.radius = radius
	@property
	def diameter(self):
		return 2 * self.radius
c = Circle(5)
print(c.radius)
print(c.diameter)
c.radius = 7
print(c.diameter)

D:\MyPython>python test2.py

5
10
14

使用名称重整保护私有特性

把hidden_name改为__name(由两个下划线开头)

# _*_ coding: utf-8_*_
class Duck():
	def __init__(self, input_name):
		self.__name = input_name
	@property
	def name(self):
		print('inside the getter')
		return self.__name
	@name.setter
	def name(self, input_name):
		print('inside the setter')
		self.__name = input_name
	
fowl = Duck('Howard')
print(fowl.name)	
fowl.name = 'Daffy'	
print(fowl.name)
print(fowl.__name) #无法访问,但是fowl._Duck__name可以访问

D:\MyPython>python test2.py

inside the getter
Howard
inside the setter
inside the getter
Daffy
Traceback (most recent call last):
  File "test2.py", line 18, in
    print(fowl.__name)
AttributeError: 'Duck' object has no attribute '__name'

方法的类型:(实例方法,类方法,静态方法)

# _*_ coding: utf-8_*_
class A():
	count = 0
	def __init__(self): #实例方法的参数是self
		A.count += 1
	def exclaim(self):
		print("I'm an A!")
	@classmethod		#类方法
	def kids(cls):	#cls表示类本身
		print("A has", cls.count, "little objects.")
easy_a = A()
breezy_a = A()
wheezy_a = A()
A.kids()

D:\MyPython>python test2.py
A has 3 little objects.

静态方法

# _*_ coding: utf-8_*_
class CoyoteWeapon():
	@staticmethod
	def commercial():
		print('This CoyoyeWeapon has been brought to you')
CoyoteWeapon.commercial()	#不需要创建类的对象就能够调用这个方法
鸭子类型
# _*_ coding: utf-8_*_
class Quote():
	def __init__(self, person, words):
		self.person = person
		self.words = words
	def who(self):
		return self.person
	def says(self):
		return self.words + '.'
class QuestionQuote(Quote):			#实现多态
	def says(self):
		return self.words + '?'
class ExclamationQuote(Quote):
	def	says(self):
		return self.words + '!'
#面向对象的语言中多态的传统形式
hunter = Quote('Elemer Fudd', "I'm hunting wabbits")
print(hunter.who(), 'says:', hunter.says())
hunter1 = QuestionQuote('Bugs Bunny', "What's up, doc")
print(hunter1.who(),'says:', hunter1.says())
hunter2 = ExclamationQuote('Daffy Duck',"It's rabbit season")
print(hunter2.who(), 'says:', hunter2.says())

#Python无论对象的种类是什么,只要包含who()和says(),就可以去调用它,鸭子类型(duck typing)
class BabblingBrook():
	def who(self):
		return 'Brook'
	def says(self):
		return 'Babble'
brook = BabblingBrook()
def who_says(obj):
	print(obj.who(),'says', obj.says())
who_says(hunter)
who_says(hunter1)
who_says(hunter2)
who_says(brook)

D:\MyPython>python test2.py
Elemer Fudd says: I'm hunting wabbits.
Bugs Bunny says: What's up, doc?
Daffy Duck says: It's rabbit season!
Elemer Fudd says I'm hunting wabbits.
Bugs Bunny says What's up, doc?
Daffy Duck says It's rabbit season!
Brook says Babble

特殊方法或者魔方方程(special method):以双下划线(__)开头和结束

# _*_ coding: utf-8_*_

#Python无论对象的种类是什么,只要包含who()和says(),就可以去调用它,鸭子类型(duck typing)
class Word():
	def __init__(self, text):
		self.text = text
	def equals(self, word2):
		return self.text.lower() == word2.text.lower() #self.text是当前Word对象所包含的字符串文本
first = Word('ha')
second = Word('HA')
third = Word('en')
print(first.equals(second))
print(first.equals(third))
class Word2():
	def __init__(self, text):
		self.text = text
	def __eq__(self, word2):
		return self.text.lower() == word2.text.lower()
first = Word2('ha')
second = Word2('HA')
third = Word2('en')
print(first == second)
print(first == third)

D:\MyPython>python test2.py
True
False
True
False

和比较相关的魔方方程
__eq__(self, other) self == other
__ne__(self, other) self != other
__lt__(self, other) self < other
__gt__(self, other) self > other
__le__(self, other) self <= other
__ge__(self, other) self >= other
和数学相关的魔术方法
__add__(self, other) self + other
__sub__(self, other) self - other
__mul__(self, other) self * other
__floordiv__(self, other) self // other
__truediv__(self, other) self / other
__mov__(self, other) self % other
__pow__(self, other) self ** other
其他种类的魔术方法
__str__(self)	str(self)
__repr__(self)	repr(self)  #交互式解释器会输出变量
__len__(self)	len(self)
class Word2():
	def __init__(self, text):
		self.text = text
	def __eq__(self, word2):
		return self.text.lower() == word2.text.lower()
first = Word2('ha')
print(first)
class Word2():
	def __init__(self, text):
		self.text = text
	def __eq__(self, word2):
		return self.text.lower() == word2.text.lower()
	def __str__(self):
		return self.text
first = Word2('ha')
print(first)

D:\MyPython>python test2.py
<__main__.Word2 object at 0x000001FACCCAA940>
ha
组合

# _*_ coding: utf-8_*_

class Bill():
	def __init__(self, description):
		self.description = description
class Tail():
	def __init__(self, length):
		self.length = length
class Duck():
	def __init__(self, bill, tail):
		self.bill = bill
		self.tail = tail
	def about(self):
		print('This duck has a', self.bill.description, 'bill and a', self.tail.length,'tail')
tail = Tail('long')
bill = Bill('wide orange')
duck = Duck(bill, tail)
duck.about()	


D:\MyPython>python test2.py
This duck has a wide orange bill and a long tail
何时使用类和对象而不是模块

当需要许多相似行为但不同状态的实例时,用对象;类支持继承,模块不支持;模块可以保证实例的唯一性,不管模块在程序中被引用多少次,始终只有一个实例被加载;如果有一系列包含多个值得变量,并且他们能作为参数传入不同的函数,最好把他们封装到类里面;使用最简单的方法解决问题,使用字典,列表和元组往往比使用模块简单和简洁,而使用类则更为复杂。

命名元组:

1.名称;2:由多个域名组成的字符串,各个域名之间由空格隔开,可以用nametuple函数来创建;

好处:跟不可变对象非常相似;与使用对象相比,使用命名元组在时间和空间上效率更高;可以把它作为字典的键;可以使用点号(.)对特性进行访问,而不需要使用字典风格的方括号。

# _*_ coding: utf-8_*_
from collections import namedtuple
Duck = namedtuple('Duck', 'bill tail')
duck = Duck('wide orange', 'long')
print(duck)
print(duck.bill)
print(duck.tail)
parts = {'bill':'wide orange', 'tail':'long'}
duck2 = Duck(**parts)	#相当于duck2 = Duck(bill='wide orange', tail='long')
print(duck2)
#命名元组是不可变的,但你可以替换其中某些域的值并返回一个新的命名元组
duck3 = duck2._replace(tail='magnificent', bill='crushing')
print(duck3)
#无法对命名元组这样做:
duck.color = 'green'


D:\MyPython>python test2.py
Duck(bill='wide orange', tail='long')
wide orange
long
Duck(bill='wide orange', tail='long')
Duck(bill='crushing', tail='magnificent')
Traceback (most recent call last):
  File "test2.py", line 16, in 
AttributeError: 'Duck' object has no attribute 'color'

本文是我在学习了丁嘉瑞的《Python语言及其应用》所做的笔记,只用于学习。



你可能感兴趣的:(Python)