Python之面向对象基础(01)

发布时间:2021-12-03 公开文章

I am not a designer nor a coder. I'm just a guy with a point-of-view and a computer.

筑基<融合<元婴<分神<渡劫<大乘

 

类与对象基础

定义类 -- 使用方法来获取属性并输出

# 定义类 -- 使用方法来获取属性并输出
class Motor:

    #定义方法一:获取名称和颜色
    def buildCar(self, name, color):
        self.name = name
        self.color = color

    #定义方法二:输出名称和颜色
    def showMessage(self):
        print('款式:{0:6s}, 颜色:{1:4s}'.format(self.name, self.color))        

# 创建对象
car1 = Motor()#对象1
car1.buildCar('Vios', '极光蓝')
car1.showMessage() #调用方法

car2 = Motor()#对象2
car2.buildCar('Altiss', '炫魅红')
car2.showMessage()
款式:Vios  , 颜色:极光蓝 
款式:Altiss, 颜色:炫魅红

定义类, 传入不同类型

# 定义类, 传入不同类型

class Student:
    def message(self, name): 
        self.data = name

    def showMessage(self):
        print(self.data)

s1 = Student()
s1.message('James McAvoy')
s1.showMessage()

s2 = Student()
s2.message(78.566)
s2.showMessage()
James McAvoy
78.566

创建类,未使用init()方法

# 创建类,未使用__init__()方法

class Student():
    def score(self, s1, s2, s3):
        return (s1 + s2 + s3)/3


Tomas = Student()#创建对象
print('Tomas平均分数:',Tomas.score(78, 96, 55))

Tomas.subject = []
Tomas.subject.extend(['math', 'eng', 'computer'])
print(Tomas.subject)
Tomas平均分数 76.33333333333333
['math', 'eng', 'computer']

先构造,再初始化对象

#先构造,再初始化对象

class newClass:
    #__new__()构建对象
    def __new__(Kind, name):

        if name != '' :
            print("对象已创建")
            return object.__new__(Kind)

        else:
            print("对象未创建")            
            return None

    #__init__()初始化对象
    def __init__(self, name):
        print('对象初始化...')
        print(name)

x = newClass('')
print('...')
y = newClass('Second')
对象未创建
...
对象已创建
对象初始化...
Second

定义类 -- 使用init()方法来获取属性并输出

#定义类 -- 使用__init__()方法来获取属性并输出

class Motor:

    #__init__():初始化对象
    def __init__(self, name, color):
        self.name = name
        self.color = color

    #定义方法二:输出名称和颜色
    def showMessage(self):
        print('款式:{0:6s}, 颜色:{1:4s}'.format(self.name, self.color))

# 创建对象
car1 = Motor('Vios', '极光蓝')#对象1
car1.showMessage() #调用方法

car2 = Motor('Altiss', '炫魅红')#对象2
car2.showMessage()
款式:Vios  , 颜色:极光蓝 
款式:Altiss, 颜色:炫魅红

定义计算圆形的面积和周长的函数

#定义计算圆形的面积和周长的函数
import math

#算出圆周长
def calcPerimeter(radius):
    return 2 * radius * math.pi

#算出圆面积
def roundArea(radius):
    return radius * radius * math.pi

print('圆周长:{0:4f}'.format(
    calcPerimeter(15)))

print('圆面积:{0:4f}'.format(
    roundArea(15)))
圆周长:94.247780
圆面积:706.858347
import math

# 定义类
class Circle:
    '''
定义类的方法
calcPerimeter : 计算圆周长
roundArea     : 计算圆面积
__init__()    : 自定义对象初始化状态 '''

    #__init__ 初始化对象    
    def __init__(self, radius = 15):
        self.radius = radius        

    def calcPerimeter(self):
        return 2 * self.radius * math.pi    

    def roundArea(self):
        return self.radius * self.radius * math.pi

#创建对象, 传入半径值
firstR = Circle(17)

print('圆的半径:', firstR.radius)
print('圆周长:{0:2f}'.format(firstR.calcPerimeter()))
print('圆面积:{0:3f}'.format(firstR.roundArea()))
圆的半径: 17
圆周长:106.814150
圆面积:907.920277
class Numbers:
    def __init__(self, value = None):
        self.num = value
        self.result = 10        

    def increase(self):
        self.result += self.num
        return self.result

    def subtract(self):
        self.result -= self.num
        return self.result

one = Numbers(5)
print("增加:", one.increase())
print("减少:", one.subtract())
print("第二次减少:", one.subtract())
增加: 15
减少: 10
第二次减少: 5

对象的属性

# 对象的属性

class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        print('Hi! ', self.name)
        print('Your age: ', self.age)

#创建对象

p1 = Person('Vicky', 25)
p1.display()
print('年龄:', getattr(p1, 'age'))
setattr(Person, 'sex', 'Female')
print('性别:', p1.sex)
Hi!  Vicky
Your age:  25
年龄: 25
性别: Female

特殊方法 str()

#特殊方法 __str__(): 

class Birth():

    def __init__(self, name, y, m, d):
        self.title = name
        self.year = y
        self.month = m
        self.date = d

    # 定义输出格式    
    def __str__(self):
        print('Hi!', self.title)
        return 'Birth - ' + str(
            self.year) + '年' + str(
            self.month)+ '月' + str(
            self.date) + '日'

    # 调用format()方法进行格式化输山
    def __repr__(self):
        return '{}年 {}月 {}日'.format(
            self.year, self.month, self.date)

#创建对象
p1 = Birth('Grace', 1987, 12, 15)
print(p1)
print(p1.title, 'birth day: ', repr(p1))
Hi! Grace
Birth - 19871215
Grace birth day:  1987 12 15
class Testing():
    #初始化对象
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y    

    def __del__(self): #destructor - 用来清除对象
        MyName = self.__class__.__name__
        print('已清除', MyName)
#创建对象
t1 = Testing(15, 20)
t2 = t1
print('t1 = ', id(t1), ', t2 = ', id(t2))
del t1
del t2
t1 =  2549617751152 , t2 =  2549617751152
已清除 Testing
print('t1 = ', id(t1), ', t2 = ', id(t2))
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-16-7b650449f67d> in <module>()
----> 1 print('t1 = ', id(t1), ', t2 = ', id(t2))


NameError: name 't1' is not defined