python day20面向对象-属性,类方法,静态方法

一、属性的初识

# class Person:
#
#     def __init__(self,name,hight,weight):
#         self.name = name
#         self.__hight = hight
#         self.__weight = weight
#
#     @property
#     def bmi(self):
#         return '%s 的bmi 值%s' %(self.name,self.__weight / self.__hight ** 2)

# p1 = Person('大阳哥',1.68,70)
# # print(p1.bmi())
# print(p1.bmi)
# # 属性  : 将一个方法  伪装成一个 属性,在代码的级别上没有本质的提升,但是让其看起来跟合理.
# print(p1.name)
# p1.name = 'alex'
# print(p1.name)
View Code

属性的更改

class Person:
    def __init__(self,name,age):
        self.name = name
        if type(age) is int:
            self.__age = age
        else:
            print( '你输入的年龄的类型有误,请输入数字')
    @property
    def age(self):
        return self.__age

    @age.setter #更改属性的值
    def age(self,a1):
        '''判断,你修改的年龄必须是数字'''
        if type(a1) is int:
            self.__age = a1
        else:
            print('你输入的年龄的类型有误,请输入数字')

    @age.deleter 删除属性
    def age(self):
        del self.__age


p1 = Person('帅哥',20)
print(p1.age)
# print(p1.__dict__)
# p1.age = 23
# print(p1.age)
del p1.age
# property : 类似于bmi这种,area,周长....名词方法里面需要计算的。  ***
# @age.setter **
# @age.deleter *

类方法:
通过类名调用的方法,类方法中第一个参数约定俗称cls,python自动将类名(类空间)传给cls.
 
# class A:
#     def func(self):  # 普通方法
#         print(self)
#
#     @classmethod  # 类方法
#     def func1(cls):
#         print(cls)

# a1 = A()

# a1.func()
# A.func(a1)#需要传参
类方法的应用场景:
1, 类中 有些方法是不需要对象参与.
class A:
    name = 'alex'
    count = 1

    @classmethod
    def func1(cls):  # 此方法无需对象参与
        return  cls.name + str(cls.count + 1)
2, 对类中的静态变量进行改变,要用类方法.

3,继承中,父类得到子类的类空间.
class A:
    age = 12
    @classmethod
    def func1(cls):  # 此方法无需对象参与
        # print(cls)
        # 对B类的所有的内容可以进行修改.
        print(cls.age)
        # return cls.name + str(cls.count + 1)

class B(A):
    age = 22
B.func1()
# 不通过类方法,想让我的父类的某个方法得到子类的类空间里面的任意值.
# class A:
#     age = 12
#
#     def func2(self):
#         print(self)  # self 子类的对象,能得到子类 空间的任意值
#
# class B(A):
#     age = 22
#
# b1 = B()
# b1.func2()
静态方法:
# class A:
#
#     @staticmethod
#     def login(username, password):
#         if username == 'alex' and password == 123:
#             print('登录成功')
#         else:
#             print('登录失败...')
#
#
# A.login('alex',1234)


#普通方法
# def login(username,password):
#     if username == 'alex' and password == 123:
#         print('登录成功')
#     else:
#         print('登录失败...')
#
# login('alex',1234)

# 1,代码块.清晰.
# 2,复用性.