Python小知识点(7)

  • 类的相关介绍
"""

class Human(object):
	phylum = 'Chordata'
	order = 'Primates'
	family = 'Human Being'


ZhangSan = Human()
"""
# 已将该实例的属性值重新定义,不会受到此后类属性值变化的影响
"""
ZhangSan.family = 'Mankind'
print(ZhangSan.family) # Mankind
# 类属性也是可以修改的
Human.family = 'Homo'
print(ZhangSan.family)# Mankind
Lily = Human()
print(Lily.family)# Homo
ZhangSan.kingdom = 'Animalia'#实例的属性可以直接添加,类的属性也是如此

"""

"""

class Human(object):
	domain = 'eukarya'
	def __init__(self, kingdom='Animalia', phylum='Chordata', 
				 order='Primates', family='Human Being'):
		self.kingdom = kingdom
		self.phylum = phylum
		self.order = order
		self.family = family
		
	# 实例方法
	# def 中都要包含self
	def typewrite(self):
		print("This is %s typing words!" %(self.family))
	def add(self, n1, n2):
		n = n1 + n2
		print(str(n1) + '+' + str(n2) + '=' + str(n))
		print('You see! %s can calculate!' %(self.family))

ZhangSan = Human()
LiSi = Human(kingdom='Animal', family='Homo')
print(LiSi.kingdom)
print(LiSi.family)
print(ZhangSan.kingdom)

"""

"""

class Human(object):
	domain = 'eukarya'
	def __init__(self, kingdom='Animalia', phylum='Chordata', 
				 order='Primates', family='Human Being'):
		self.kingdom = kingdom
		self.phylum = phylum
		self.order = order
		self.family = family
	def typewrite(self):
		print("This is %s typing words!" %(self.family))
	def add(self, n1, n2):
		n = n1 + n2
		print(str(n1) + '+' + str(n2) + '=' + str(n))
		print('You see! %s can calculate!' %(self.family))
	# 类方法
	# 第一个参数为cls,表示类本身
	# 定义类方法时,使用@classmethod 装饰器
	@classmethod
	def showclassmethodinfo(cls):
		print(cls.__name__) # __name__属性,其值为名
		print(dir(cls)) # 展示本类的所有方法

ZhangSan = Human()
print(ZhangSan.showclassmethodinfo())
print(Human.showclassmethodinfo())
"""
"""
Human
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'add', 'domain', 'showclassmethodinfo', 'typewrite']
None
Human
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'add', 'domain', 'showclassmethodinfo', 'typewrite']
None
"""
"""

"""

"""

class Human(object):
	domain = 'eukarya' # 类属性(可通过类名,实例访问)
	def __init__(self, kingdom='Animalia', phylum='Chordata', 
				 order='Primates', family='Human Being'):
		self.kingdom = kingdom # 实例属性(只能通过实例访问)
		self.phylum = phylum
		self.order = order
		self.family = family
	def typewrite(self):
		print("This is %s typing words!" %(self.family))
	def add(self, n1, n2):
		n = n1 + n2
		print(str(n1) + '+' + str(n2) + '=' + str(n))
		print('You see! %s can calculate!' %(self.family))
	
	@classmethod
	def showclassmethodinfo(cls):
		print(cls.__name__) 
		print(dir(cls))
	
	# 静态方法
	# 无参数
	# 定义类方法时,使用@staticmethod 装饰器
	
	@staticmethod
	def showclassattributeinfo():
		print(Human.__dict__) # __dict__属性,返回键名为属性名,键值为属性值的字典
							  # 双下划线前后缀的属性为自带的特殊的类属性
ZhangSan = Human()
print(ZhangSan.showclassattributeinfo())
print(Human.showclassattributeinfo())

"""

class Human(object):
	domain = 'eukarya' # 类属性(可通过类名,实例访问)
	def __init__(self, kingdom='Animalia', phylum='Chordata', 
				 order='Primates', family='Human Being'):
		self.kingdom = kingdom # 实例属性(只能通过实例访问)
		self.phylum = phylum
		self.__order = order # 私有属性
		self.family = family
	def typewrite(self):
		print("This is %s typing words!" %(self.family))
	def add(self, n1, n2):
		n = n1 + n2
		print(str(n1) + '+' + str(n2) + '=' + str(n))
		print('You see! %s can calculate!' %(self.family))
	
	@classmethod
	def showclassmethodinfo(cls):
		print(cls.__name__) 
		print(dir(cls))
	
	@staticmethod
	def showclassattributeinfo():
		print(Human.__dict__) 

"""		
ZhangSan = Human()
print(ZhangSan._Human__order) # Primates
print(ZhangSan.order) #与ZhanSan.__order结果相同,错误
"""

# 隐式继承
# 完全继承所有成员
# 隐式继承中,父类的私有成员不能继承
# 如果在子类中使用__init__来构造实例属性时,一定要用super函数去初始化父类
class Male(Human):
	def __init__(self, gender='male'):
		super(Male, self).__init__()# super函数的第一个参数是父类的名字
		self.gender = gender
	def add(self, n1, n2):
		# 在子类中重新定义add方法
		n = n1 - n2
		print(str(n1) + '-' + str(n2) + '=' + str(n))
		print('You see! %s can NOT use addition!' %(self.gender))
		
someoneismale = Male()
print(someoneismale.family)# Human Being
print(someoneismale.kingdom)# Animalia
print(someoneismale.add(1, 1))
# 父类的实例与子类不是同一个类型
# 子类的实例与父类是同类
# 继承与同一个父类的子类是不同类


# 调用对象的add方法
def addition(obj, n1, n2):
	obj.add(n1, n2)
addition(someoneismale, 1, 1)
addition(Male(), 1, 1)


  • 说明文档格式

def remove(self, item):
	"""
	   Precondition: item is in self. 先验条件(只有该语句为真的时候,方法才能够正确地执行操作)
	   Raises: KeyError if item in not in self.  用来说明可能发生的异常,通常是无法满足方法的先验条件而导致的结果
	   Postcondition: item is removed from self. 后验条件(当方法执行完毕后,变为了什么情况)
	"""
  • 解包

>>> a, b, c = "jkl"
>>> a
'j'
>>> b
'k'
>>> c
'l'

>>> a, b, c = ['j', 'k', (1, 2, 3)]
>>> a
'j'
>>> b
'k'
>>> c
(1, 2, 3)

>>> record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')
>>> name, email, *phone_numbers = record
>>> name
'Dave'
>>> email
'dave@example.com'
>>> phone_numbers
['773-555-1212', '847-555-1212']

>>> *trailing, current = [10, 8, 7, 1, 9, 5, 10, 3]
>>> trailing
[10, 8, 7, 1, 9, 5, 10]
>>> current
3

>>> record = ('ACME', 50, 123.45, (12, 18, 2012))
>>> name, *_, (*_, year) = record
>>> name
'ACME'
>>> year
2012
from collections import deque
q = deque(maxlen=3)
q.append(3)
q.appendleft(3)
q.pop()
q.popleft()

>>> import heapq
>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
>>> print(heapq.nlargest(2, nums))
[42, 37]
>>> print(heapq.nsmallest(2, nums))
[-4, 1]

import heapq
portfolio = [
	{'name':'IBM', 'shares':100, 'price':91.1},
	{'name':'AAPL', 'shares':50, 'price':543.22},
	{'name':'FB', 'shares':200, 'price':21.09},
	{'name':'HPQ', 'shares':35, 'price':31.75},
	{'name':'YHOO', 'shares':45, 'price':16.35},
	{'name':'ACME', 'shares':75, 'price':115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
print(cheap, '\n', expensive)
"""
[{'shares': 45, 'name': 'YHOO', 'price': 16.35}, {'shares': 200, 'name': 'FB', 'price': 21.09}, {'shares': 35, 'name': 'HPQ', 'price': 31.75}]
 [{'shares': 50, 'name': 'AAPL', 'price': 543.22}, {'shares': 75, 'name': 'ACME', 'price': 115.65}, {'shares': 100, 'name': 'IBM', 'price': 91.1}]
"""

# 优先级队列的实现
import heapq
class PriorityQueue:
	
	def __init__(self):
		self._queue = []
		self._index = 0
		
	def push(self, item, priority):
		heapq.heappush(self._queue, (-priority, self._index, item))
		self._index += 1
	
	def pop(self):
		return heapq.heappop(self._queue)[-1]
		
# 如何使用
class Item:
	def __init__(self, name):
		self.name = name
	def __repr__(self):
		return 'Item({!r})'.format(self.name)
q= PriorityQueue()
q.push(Item('foo'), 1)
q.push(Item('bar'), 5)
q.push(Item('spam'), 4)
q.push(Item('grok'), 1)
for i in range(4):
	print(q.pop())
"""
Item('bar')
Item('spam')
Item('foo')
Item('grok')
"""
  • 特殊变量

_xxx 不能用 from module import* 导入
xxx 系统定义名字
__xxx 类中私有变量名

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jia ming

谢谢投食哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值