#!/usr/bin/python3
import time
class MyClass:
"""一个简单的类实例"""
def __init__(self,i):
self.input = i
def f(self):
return 'hello world'
# 实例化类
x = MyClass(123)
# 访问类的属性和方法
print("MyClass 类的属性 i 为:", x.input)
print("MyClass 类的方法 f 输出为:", x.f())
#######################################################################
class Myclass2:
i = 12345
x = Myclass2()
print(print("MyClass 类的属性 i 为:", x.i))
#######################################################################
# 简单的类
class VehicleState:
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0):
self.x = x
self.y = y
self.yaw = yaw
self.v = v
state = VehicleState(yaw = 11,y = 12)
print("vehicle initial yaw state is",state.yaw)
print("vehicle initial y state is",state.y)
# !/usr/bin/python3
class Complex:
def __init__(self, real_part, imag_part):
self.r = real_part
self.i = imag_part
x = Complex(3.0, -4.5)
print(x.r, x.i) # 输出结果:3.0 -4.5
#######################################################################
# !/usr/bin/python3 简单的类
# 类定义
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 说: 我 %d 岁。" % (self.name, self.age))
# 实例化类
p = people('runoob', 10, 30)
p.speak()
#######################################################################
# !/usr/bin/python3 单继承
# 类定义
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 说: 我 %d 岁 and weight %d。" % (self.name, self.age,self.__weight))
p = people('runoob', 10, 30)
p.speak()
# 单继承示例
class student(people):
grade = ''
def __init__(self, n, a, w, g):
# 调用父类的构函
people.__init__(self, n, a, w)
super().__init__(n, a, w)
self.grade = g
# 覆写父类的方法
def speak2(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级" % (self.name, self.age, self.grade))
s = student('ken', 10, 60, 3)
s.speak2()
s.speak()
#######################################################################
# !/usr/bin/python3 多继承
# 类定义
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 说: 我 %d 岁。" % (self.name, self.age))
# 单继承示例
class student(people):
grade = ''
def __init__(self, n, a, w, g):
# 调用父类的构函
people.__init__(self, n, a, w)
super().__init__(n, a, w)
self.grade = g
# 覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级" % (self.name, self.age, self.grade))
# 另一个类,多重继承之前的准备
class speaker():
topic = ''
name = ''
def __init__(self, n, t):
self.name = n
self.topic = t
def speak(self):
print("我叫 %s,我是一个演说家,我演讲的主题是 %s" % (self.name, self.topic))
# 多重继承
class sample(speaker, student):
a = ''
def __init__(self, n, a, w, g, t):
student.__init__(self, n, a, w, g)
speaker.__init__(self, n, t)
test = sample("Tim", 25, 80, 4, "Python")
test.speak() # 方法名同,默认调用的是在括号中排前地父类的方法
#######################################################################
# !/usr/bin/python3 如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法,实例如下:
class Parent: # 定义父类
def myMethod(self):
print('调用父类方法')
class Child(Parent): # 定义子类
def myMethod(self):
print('调用子类方法')
c = Child() # 子类实例
c.myMethod() # 子类调用重写方法
super(Child, c).myMethod() # 用子类对象调用父类已被覆盖的方法
#######################################################################
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) # 报错,实例不能访问私有变量
########################################################################!/usr/bin/python3
class Site:
def __init__(self, name, url):
self.name = name # public
self.__url = url # private
def who(self):
print('name : ', self.name)
print('url : ', self.__url)
def __foo(self): # 私有方法
print('这是私有方法')
def foo(self): # 公共方法
print('这是公共方法')
self.__foo()
x = Site('菜鸟教程', 'www.runoob.com')
x.who() # 正常输出
x.foo() # 正常输出
# x.__foo() # 报错
from transitions import Machine
class Matter(object):
pass
model = Matter()
#The states argument defines the name of states
states=['solid', 'liquid', 'gas', 'plasma']
# The trigger argument defines the name of the new triggering method
transitions = [
{'trigger': 'melt', 'source': 'solid', 'dest': 'liquid' },
{'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas'},
{'trigger': 'break', 'source': 'solid', 'dest': 'gas'},
{'trigger': 'ionize', 'source': 'gas', 'dest': 'plasma'}]
machine = Machine(model=model, states=states, transitions=transitions, initial='solid')
# Test
print(model.state) # solid
model.melt()
print(model.state) # liquid
model.evaporate()
print(model.state) #gas
########################################################################!/usr/bin/python3
class Car:
# 移动
def move(self):
print('车在奔跑...')
# 鸣笛
def toot(self):
print("车在鸣笛...嘟嘟..")
# 创建一个对象,并用变量BMW来保存它的引用
BMW = Car()
BMW.color = '黑色'
BMW.wheelNum = 4 #轮子数量
BMW.move()
BMW.toot()
print(BMW.color)
print(BMW.wheelNum)
########################################################################!/usr/bin/python3
class SweetPotato:
'这是烤地瓜的类'
#定义初始化方法
def __init__(self):
self.cookedLevel = 0
self.cookedString = "生的"
self.condiments = []
#烤地瓜方法
def cook(self, time):
self.cookedLevel += time
if self.cookedLevel > 8:
self.cookedString = "烤成灰了"
elif self.cookedLevel > 5:
self.cookedString = "烤好了"
elif self.cookedLevel > 3:
self.cookedString = "半生不熟"
else:
self.cookedString = "生的"
# 用来进行测试
mySweetPotato = SweetPotato()
for i in range(10):
mySweetPotato.cook(1)
print("烧烤等级", mySweetPotato.cookedLevel)
print(mySweetPotato.cookedString)
time.sleep(0.01)
class item:
area = 0
def __init__(self, area):
self.area = area
def get_area(self):
print("this one area is", self.area)
return self.area
class Home:
area = 0
bed_area = 0
def __init__(self, area, bed_area):
self.area = area
self.bed_area = bed_area
def update(self):
if self.area >= self.bed_area:
self.area = self.area - self.bed_area
print("add one thimg,left area is",self.area)
else:
print('no more area')
return self.area
bed = item(20)
bed_area = bed.get_area()
home = Home(100,bed_area)
home_area = home.update()
bed2 = item(20)
bed_area = bed2.get_area()
home = Home(home_area,bed_area)
home_area = home.update()
bed3 = item(120)
bed_area = bed3.get_area()
home = Home(home_area,bed_area)
home_area = home.update()
########################################################################!/usr/bin/python3
class People:
def __init__(self, name):
self.__name = name
def getName(self):
return self.__name
def setName(self, newName):
if len(newName) >= 5:
self.__name = newName
else:
print("error:名字长度需要大于或者等于5")
return self.__name
xiaoming = People("dongGe")
xiaoming.setName("wangger")
NAME = xiaoming.getName()
print("NAME is",NAME)
xiaoming.setName("LISA")
print(xiaoming.getName())
########################################################################!/usr/bin/python3
class Cat(object):
name = ""
color = ""
def __init__(self, name, color = 'baise'):
self.name = name
self.color = color
def run(self):
print("%s--在跑"%self.name)
def eat(self):
print("%s--在吃"%self.name)
# 定义一个子类,继承Cat类如下:
class Bosi(Cat):
def setNewName(self, newName):
self.name = newName
print(self.name)
bs = Bosi("印度猫","白色")
print('bs的名字为:%s'%bs.name)
print('bs的颜色为:%s'%bs.color)
bs.eat()
bs.run()
bs.setNewName('波斯猫')
bs.run()
bs.eat()
########################################################################!/usr/bin/python3
class Animal():
def __init__(self, name='动物', color='白色'):
self.__name = name
self.color = color
def __test(self):
print(self.__name)
print(self.color)
def test(self):
print(self.__name)
print(self.color)
class Dog(Animal):
def dogTest1(self):
#print(self.__name) #不能访问到父类的私有属性
print(self.color)
def dogTest2(self):
#self.__test() #不能访问父类中的私有方法
self.test()
A = Animal()
#print(A.__name) #程序出现异常,不能访问私有属性
print(A.color)
#A.__test() #程序出现异常,不能访问私有方法
A.test()
print("------分割线-----")
D = Dog(name = "小花狗", color = "黄色")
D.dogTest1()
D.dogTest2()
########################################################################!/usr/bin/python3
# 定义一个父类
class A:
def printA(self):
print('----A----')
# 定义一个父类
class B:
def printB(self):
print('----B----')
# 定义一个子类,继承自A、B
class C(A,B):
def printC(self):
print('----C----')
obj_C = C()
obj_C.printA()
obj_C.printB()
########################################################################!/usr/bin/python3
#coding=utf-8
class base(object):
def test(self):
print('----base test----')
class A(base):
def test(self):
print('----A test----')
# 定义一个父类
class B(base):
def test(self):
print('----B test----')
# 定义一个子类,继承自A、B
class C(A,B):
pass
obj_C = C()
obj_C.test()
print(C.__mro__) #可以查看C类的对象搜索方法时的先后顺序
########################################################################!/usr/bin/python3
#coding=utf-8
class Cat(object):
def sayHello(self):
print("halou-----1")
class Bosi(Cat):
def sayHello(self):
print("halou-----2")
bosi = Bosi()
bosi.sayHello()
########################################################################!/usr/bin/python3
#coding=utf-8
class Cat(object):
def __init__(self,name):
self.name = name
self.color = 'yellow'
class Bosi(Cat):
def __init__(self,name):
# 调用父类的__init__方法1(python2)
#Cat.__init__(self,name)
# 调用父类的__init__方法2
#super(Bosi,self).__init__(name)
# 调用父类的__init__方法3
super().__init__(name)
def getName(self):
return self.name
bosi = Bosi('xiaohua')
print(bosi.name)
print(bosi.color)
########################################################################!/usr/bin/python3
class People():
country = 'china'
#类方法,用classmethod来进行修饰
@classmethod
def getCountry(cls):
return cls.country
@classmethod
def setCountry(cls,country):
cls.country = country
@staticmethod
#静态方法
def setCountry2(country):
country = country
p = People()
print(p.getCountry()) #可以用过实例对象引用
print (People.getCountry()) #可以通过类对象引用
p.setCountry('japan')
print (p.getCountry())
print (People.getCountry())
p.setCountry('norway')
print (p.getCountry())
########################################################################!/usr/bin/python3
#coding=utf-8
try:
print('-----test--1---')
open('123.txt','r') # 如果123.txt文件不存在,那么会产生 IOError 异常
print('-----test--2---')
print(num)# 如果num变量没有定义,那么会产生 NameError 异常
except (IOError,NameError) as result:
print('we find io_error',result)
print("we find name error")
#如果想通过一次except捕获到多个异常可以用一个元组的方式
########################################################################!/usr/bin/python3
try:
f = open('test.txt')
try:
while True:
content = f.readline()
if len(content) == 0:
break
time.sleep(2)
print(content)
except:
#如果在读取文件的过程中,产生了异常,那么就会捕获到
#比如 按下了 ctrl+c
pass
finally:
f.close()
print('关闭文件')
except:
print("没有这个文件")
########################################################################!/usr/bin/python3
def test1():
print("----test1-1----")
print(num)
print("----test1-2----")
def test2():
print("----test2-1----")
test1()
print("----test2-2----")
def test3():
try:
print("----test3-1----")
test1()
print("----test3-2----")
except Exception as result:
print("捕获到了异常,信息是:%s"%result)
print("----test3-2----")
test3()
print("------华丽的分割线-----")
########################################################################!/usr/bin/python3
class ShortInputException(Exception):
'''自定义的异常类'''
def __init__(self, length, atleast):
#super().__init__()
self.length = length
self.atleast = atleast
def main():
try:
s = input('请输入 --> ')
if len(s) < 3:
# raise引发一个你定义的异常
raise ShortInputException(len(s), 3)
except ShortInputException as result:#x这个变量被绑定到了错误的实例
print('ShortInputException: 输入的长度是 %d,长度至少应是 %d'% (result.length, result.atleast))
else:
print('没有异常发生.')
main()
########################################################################!/usr/bin/python3
Python的类示例
猜你喜欢
转载自blog.csdn.net/gophae/article/details/104247767
今日推荐
周排行