Python的類示例

#!/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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章