标签:输出 自动 派生类 绑定 经典 机械 run 课程 name
class 类名:
"""
注释
"""
类体(可是任意代码)
# 定义一个类
class Chinese:
country = ‘China‘ # 属性
def __init__(self, name, age): # 初始化,实例化出来的对象默认拥有name,age等属性
self.name = name # p1.name=name
self.age = age
# p1.age=age
def talk(self): # 技能
print(‘say Chinese‘)
p1 = Chinese(‘rain‘, 18) # 实例化出一个对象p1
print(p1.country) # 类的数据属性
print(p1.talk()) # 类的函数属性,加括号即可运行
print(p1.name)
print(p1.age)
print(Chinese.__dict__)
运行结果:(一个字典)
{‘talk‘: <function Chinese.talk at 0x0000000000B4E268>, ‘country‘: ‘China‘, ‘__doc__‘: None, ‘__dict__‘: <attribute ‘__dict__‘ of ‘Chinese‘ objects>, ‘__init__‘: <function Chinese.__init__ at 0x0000000000B4E1E0>, ‘__module__‘: ‘__main__‘, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘Chinese‘ objects>}
class Foo:
count = 0
# 类的数据属性 def __init__(self, name):
Foo.count += 1
self.name = name
obj1 = Foo(‘rain‘)
obj2 = Foo(‘tom‘)
print(‘该类共实例化了 %s 个对象.‘ % Foo.count)
运行结果:
该类共实例化了 2 个对象.
class Garen:
camp = ‘Demacia‘ # 定义通用属性:阵营
def __init__(self, nickname, life_value=600, agg = 100):
self.nickname = nickname
self.life_value = life_value
self.agg = agg
def attack(self, enemy):
# 定义攻击方法,攻击敌人 enemy.life_value -= self.agg
class Riven:
camp = ‘Noxus‘
def __init__(self, nickname, life_value=400, agg = 150):
self.nickname = nickname
self.life_value = life_value
self.agg = agg
def attack(self, enemy):
enemy.life_value -= self.agg
g = Garen(‘德码‘)
r = Riven(‘瑞文‘)
print(g.life_value) # 查看血量值
print(r.life_value)
g.attack(r) # 模拟攻击
print(r.life_value) # 攻击后血量值
r.attack(g)
print(g.life_value)
class ParentClass1:
pass
class ParentClass2:
pass
class SubClass1(ParentClass1):
"""
继承父类1
"""
pass
class SubClass2(ParentClass1, ParentClass2): # 调用时,会按照从左到右顺序查找
"""
继承2个父类:父类1和父类2
"""
pass
新式类:
class Foo(object):
pass
经典类:
class Foo:
pass
Python3中都为新式类
class Foo:
pass
print(Foo.__dict__())
class E:
def test(self):
print(‘from E‘)
pass
class A(E):
def test(self):
print(‘from A‘)
pass
class D:
def test(self):
print(‘from D‘)
pass
class B(D):
def test(self):
print(‘from B‘)
pass
class C:
def test(self):
print(‘from C‘)
pass
# 优先找F自己类中的test函数,F类中没有,找A-->D,D没有回来找B-->E,还没有找C
class F(A, B, C):
def test(self):
print(‘from F‘)
pass
f = F()
f.test()
class People: # 定义父类
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
class Teacher(People): # 子类继承父类,且有自己的独特的属性salary
def __init__(self, name, age, sex, salary):
People.__init__(self, name, age, sex)
self.salary = salary
class Student(People):
# 子类继承父类 pass
t = Teacher(‘rain‘, 19, ‘male‘, 3000)
print(t.salary)
s = Student(‘a‘, 10, ‘male‘)
print(s.name)
print(s.age)
print(s.sex)
运行结果:
3000
a
10
male
class Foo:
def test(self):
print(‘from foo.test...‘)
class Bar(Foo): # 如果有多个父类,按照从左到右顺序查找,print(Bar.mro())可查看查看顺序
def test(self):
super().test()
# Foo.test(self) print(‘from Bar...‘)
b = Bar()
b.test()
运行结果:
from foo.test...
from Bar...
class Date:
def __init__(self, year, mon, day):
self.year = year
self.mon = mon
self.day = day
def tell(self):
print(‘%s-%s-%s‘ % (self.year, self.mon, self.day))
class People:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
class Teacher(People):
def __init__(self, name, age, sex, salary, year, mon, day):
People.__init__(self, name, age, sex)
self.salary = salary
self.birth = Date(year, mon, day)
class Student(People):
def __init__(self, name, age, sex, year, mon, day):
People.__init__(self, name, age, sex)
self.birth = Date(year, mon, day)
t = Teacher(‘rain‘, 19, ‘male‘, 10000, 1990, 6,20)
print(t.salary)
t.birth.tell()
s = Student(‘a‘, 11, ‘male‘, 2007, 12, 12)
print(s.name)
s.birth.tell()
运行结果:
1000
1990-6-20
a
2007-12-12
class Animal:
def talk(self):
print(‘发声...‘)
class People(Animal):
def talk(self):
print(‘人在说话...‘)
class Pig(Animal):
def talk(self):
print(‘猪在叫...‘)
class Dog(Animal):
def talk(self):
print(‘狗在叫...‘)
class Cat(Animal):
def talk(self):
print(‘猫在叫...‘)
def func(obj):
"""
统一接口
obj具有多态性,没有类型概念
:param obj:
:return:
"""
obj.talk()
peo1 = People()
dog1 = Dog()
pig1 = Pig()
cat1 = Cat()
# peo1.talk()
# dog1.talk()
# pig1.talk()
func(peo1)
func(dog1)
func(pig1)
func(cat1)
运行结果:
人在说话...
狗在叫...
猪在叫...
猫在叫...
class Foo:
__x = 1
def test(self):
print(‘from test...‘)
print(Foo.__dict__) # {‘_Foo__x‘: 1}
print(Foo._Foo__x) # 1
class People:
"""
变形仅在定义阶段完成,后续不再变形
"""
def __init__(self, name, age, sex):
self.__name = name # self._People__name = name
self.__age = age
# self._People__age = age self.__sex = sex
# self._People__sex = sex
def tell_info(self):
print(‘人的名字是:%s, 人的性别是: %s, 人的年龄是: %s‘ % (self.__name, self.__sex, self.__age))
p = People(‘rain‘, 18, ‘male‘)
p.tell_info()
运行结果:
人的名字是:rain, 人的性别是: male, 人的年龄是: 18
class Parent:
def foo(self):
"""
# 那么我要让他调用父类中的bar呢
改成self.__bar()
:return:
"""
print(‘from parent foo...‘)
self.bar() # self._Parent__bar
def bar(self): # _Parent__bar
"""
改成def __bar(self):
:return:
"""
print(‘from parent bar...‘)
class Sub(Parent):
def bar(self): # _Sub__bar
print(‘from sub bar...‘)
a = Sub()
a.foo() # 默认按照查找顺序,对象本身-->对象所属的类-->父类:from sub bar...
class People:
def __init__(self, name, age):
self.__name = name
self.__age = age
def tell_info(self):
print(‘人的名字是:%s, 人的年龄是: %s‘ % (self.__name, self.__age))
def set_info(self, x, y):
"""
我们为了限制输入的类型:
比如名字规定必须是字符串,年龄必须是整形,
就需要加一点逻辑判断:isinstance(a,b)
:param x:
:param y:
:return:
"""
if not isinstance(x, str):
raise TypeError(‘名字必须是字符串...‘)
if not isinstance(y, int):
raise TypeError(‘年龄必须是整形...‘)
self.__name = x
self.__age = y
p = People(‘alex‘, 1000)
p.tell_info()
p.set_info(‘alex‘, 2000) # 修改
p.tell_info()
p.set_info(1111, 3000) # TypeError: 名字必须是字符串...
p.tell_info()
p.set_info(‘alex‘, ‘3000‘) # TypeError: 年龄必须是整形...
p.tell_info()
class Foo:
@property
def test(self):
print(‘from Foo.test...‘)
f = Foo()
#f.test() # 结果:from Foo.test...
f.test # 结果:from Foo.test...
class People:
def __init__(self, name, weight, height):
self.name = name
self.weight = weight
self.height = height
return self.weight / (self.height ** 2)
p = People(‘rain‘, 75, 1.80)
运行结果:
23.148148148148145
import math
class Circle:
def __init__(self, radius): # 圆的半径radius
self.radius = radius
@property
def area(self): # 计算圆的面积
return math.pi * self.radius ** 2
@property
def perimeter(self): # 计算圆的周长
return 2 * math.pi * self.radius
c = Circle(10)
print(c.radius)
print(c.area)
print(c.perimeter)
运行结果:
10
314.1592653589793
62.83185307179586
class People:
def __init__(self, name, permission=False):
self.__name = name # 可转换为:self._People__name = name
self.permission = permission # 用于判断,是否允许删除
@property # 可转换为:name = property(name)
def name(self):
return self.__name # 可转换为:self._People__name
@name.setter # name = name.setter(name)
def name(self, value):
if not isinstance(value, str): # 判断value是否是字符串
raise TypeError(‘输入的内容必须是字符串.‘)
self.__name = value # self._People__name = value
@name.deleter
def name(self):
if not self.permission:
raise TypeError(‘禁止删除.‘)
del self.__name
print(‘已删除名字‘)
p = People(‘rain‘)
print(p.name())
print(p.name)
p.name = ‘rain656‘
print(p.name)
p.name = 123123
print(p.name)
p.permission = True
del p.name
print(p.name)
import hashlib
import time
class MySQL:
def __init__(self,host,port):
self.id=self.create_id()
self.host=host
self.port=port
@staticmethod
def create_id(): #就是一个普通工具
m=hashlib.md5(str(time.clock()).encode(‘utf-8‘))
return m.hexdigest()
print(MySQL.create_id)
conn=MySQL(‘127.0.0.1‘,3306)
print(conn.create_id)
运行结果:
<function MySQL.create_id at 0x0000000000D6E378>
<function MySQL.create_id at 0x0000000000D6E378>
HOST=‘127.0.0.1‘
PORT=3306
DB_PATH=r‘C:\Users\Administrator\PycharmProjects\test\面向对象编程\test1\db‘
import settings
import hashlib
import time
class MySQL:
def __init__(self, host, port):
self.host = host
self.port = port
@classmethod
def from_conf(cls):
print(cls)
return cls(settings.HOST, settings.PORT)
print(MySQL.from_conf)
conn=MySQL.from_conf()
print(conn.host, conn.port)
conn.from_conf() #对象也可以调用,但是默认传的第一个参数仍然是类
运行结果:
<bound method MySQL.from_conf of <class ‘__main__.MySQL‘>>
<class ‘__main__.MySQL‘>
127.0.0.1 3306
<class ‘__main__.MySQL‘>
import settings
class MySQL:
def __init__(self, host, port):
self.host = host
self.port = port
@staticmethod
def from_conf():
return MySQL(settings.HOST,settings.PORT)
@classmethod
def from_conf(cls):
return cls(settings.HOST,settings.PORT)
def __str__(self):
return ‘就不告诉你...‘
class Mariadb(MySQL):
def __str__(self):
return ‘host:%s, port: %s‘ %(self.host,self.port)
m=Mariadb.from_conf()
print(m)
运行结果:
# @classmethod存在时运行结果:host:127.0.0.1, port: 3306
# @classmethod不存在时运行结果:就不告诉你...
import settings
import hashlib
import time
import random
import pickle
import os
class MySQL:
def __init__(self,host,port):
self.id=self.create_id()
self.host=host
self.port=port
def save(self):
file_path=r‘%s%s%s‘ %(settings.DB_PATH,os.sep,self.id)
pickle.dump(self,open(file_path,‘wb‘))
def get(self):
file_path=r‘%s%s%s‘ %(settings.DB_PATH,os.sep,self.id)
return pickle.load(open(file_path,‘rb‘))
@staticmethod
def create_id():
m=hashlib.md5(str(time.clock()).encode(‘utf-8‘))
return m.hexdigest()
@classmethod
def from_conf(cls):
print(cls)
return cls(settings.HOST,settings.PORT)
print(MySQL.from_conf) #<bound method MySQL.from_conf of <class ‘__main__.MySQL‘>>
conn=MySQL.from_conf()
print(conn.id)
print(conn.create_id())
print(MySQL.create_id())
conn.save()
obj=conn.get()
print(obj.id)
运行结果:
<bound method MySQL.from_conf of <class ‘__main__.MySQL‘>>
<class ‘__main__.MySQL‘>
36d644ee6ae993da6a1e9530bbd7edfe
387747d3e0c9034e68cb459b89322364
578a0ec95b1d051128dcdfba3f673754
36d644ee6ae993da6a1e9530bbd7edfe
import time
class Date:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
@staticmethod
def now():
t=time.localtime()
return Date(t.tm_year,t.tm_mon,t.tm_mday)
@staticmethod
def tomorrow():
t=time.localtime(time.time()+86400)
return Date(t.tm_year,t.tm_mon,t.tm_mday)
a=Date(‘1987‘,11,21)
b=Date.now()
c=Date.tomorrow()
print(a.year,a.month,a.day)
print(b.year,b.month,b.day)
print(c.year,c.month,c.day)
运行结果:
1987 11 21
2017 6 13
2017 6 14
import time
class Date:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
@staticmethod
def now():
t=time.localtime()
return Date(t.tm_year,t.tm_mon,t.tm_mday)
class EuroDate(Date):
def __str__(self):
return ‘year:%s month:%s day:%s‘ %(self.year,self.month,self.day)
e=EuroDate.now()
print(e) #我们的意图是想触发EuroDate.__str__,但是结果为
‘‘‘
输出结果:
<__main__.Date object at 0x1013f9d68>
‘‘‘
#因为e就是用Date类产生的,所以根本不会触发EuroDate.__str__,解决方法就是用classmethod
import time
class Date:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
# @staticmethod
# def now():
# t=time.localtime()
# return Date(t.tm_year,t.tm_mon,t.tm_mday)
@classmethod #改成类方法
def now(cls):
t=time.localtime()
return cls(t.tm_year,t.tm_mon,t.tm_mday) #哪个类来调用,即用哪个类cls来实例化
class EuroDate(Date):
def __str__(self):
return ‘year:%s month:%s day:%s‘ %(self.year,self.month,self.day)
e=EuroDate.now()
print(e) #我们的意图是想触发EuroDate.__str__,此时e就是由EuroDate产生的,所以会如我们所愿
运行结果:
<__main__.Date object at 0x0000000000AA0908>
year:2017 month:6 day:13
class Chinese:
country = ‘China‘
def __init__(self,name,age):
self.name=name
self.age=age
p=Chinese(‘jack‘, 19)
print(Chinese.country) # 可转换为Chinese.__dict__[‘country]
print(p.name) # 可转换为p.__dict__[‘name‘]
class BlackMedium:
feature=‘Ugly‘
def __init__(self,name,addr):
self.name=name
self.addr=addr
def sell_house(self):
print(‘%s 黑中介卖房子啦,傻逼才买呢,但是谁能证明自己不傻逼.‘ % self.name)
def rent_house(self):
print(‘%s 黑中介租房子啦,傻逼才租呢.‘ % self.name)
# 检测是否含有某个属性
b1 = BlackMedium(‘万成‘,‘回龙观‘)
print(hasattr(b1,‘name‘)) # 判断对象b1是否有‘name‘这个属性,判断的属性必须是字符串形式
print(hasattr(b1,‘sell_house‘))
# 获取某个属性
n = getattr(b1,‘name‘)
print(n)
func=getattr(b1,‘rent_house‘)
func()
# getattr(b1,‘aaaaa‘) # 提示报错
print(getattr(b1,‘aaaaa‘,‘不存在...‘)) # 提示‘不存在‘
# 设置某个属性
setattr(b1,‘sb‘,True) # 设置对象b1的属性‘sb‘,值为True
setattr(b1,‘show_name‘,lambda self:self.name+‘sb‘) # 设置b1属性‘show_name‘
print(b1.__dict__) # 查看对象b1的属性字典
print(b1.show_name(b1))
# 删除属性
delattr(b1,‘addr‘)
delattr(b1,‘show_name‘)
# delattr(b1,‘show_name111‘) # 不存在则报错
print(b1.__dict__)
class Foo(object):
staticField = "old boy"
def __init__(self):
self.name = ‘wupeiqi‘
def func(self):
return ‘func‘
@staticmethod
def bar():
return ‘bar‘
print getattr(Foo, ‘staticField‘)
print getattr(Foo, ‘func‘)
print getattr(Foo, ‘bar‘)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
def s1():
print ‘s1‘
def s2():
print ‘s2‘
this_module = sys.modules[__name__]
hasattr(this_module, ‘s1‘)
getattr(this_module, ‘s2‘)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def test():
print(‘from the test‘)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
程序目录:
module_test.py
index.py
当前文件:
index.py
"""
import module_test as obj
#obj.test()
print(hasattr(obj,‘test‘))
getattr(obj,‘test‘)()
class FtpClient:
‘ftp客户端,但是还么有实现具体的功能‘
def __init__(self,addr):
print(‘正在连接服务器[%s]‘ %addr)
self.addr=addr
import ftpclient
f1=ftpclient.FtpClient(‘192.168.1.1‘)
if hasattr(f1,‘get‘):
func_get=getattr(f1,‘get‘)
func_get()
class FtpCLient:
def __init__(self,host):
self.host=host
print(‘connecting...‘)
def run(self):
while True:
inp=input(‘>>: ‘).strip()
inp_l=inp.split()
if hasattr(self,inp_l[0]):
func=getattr(self,inp_l[0])
func(inp_l)
def get(self,arg):
print(‘download file‘,arg[1])
f=FtpCLient(‘192.168.1.2‘)
f.run()
标签:输出 自动 派生类 绑定 经典 机械 run 课程 name
原文地址:http://www.cnblogs.com/xiaofeiweb/p/7029398.html