Python面向对象

时间:2019-03-18
本文章向大家介绍Python面向对象,主要包括Python面向对象使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
# (1)定义类:在PPython中可以使用class来创建一个专门类
class Acount:
    pass
def account(name,number,balance):
    aact=Acount()
    aact.name=name
    aact.number=number
    acct.balance=balance
    return aact
def deposit(acct,amount):
    if amount <= 0:
        print("存款金额不得为负")
    else:
        acct.balance +=amount
def withdrow(acct,amount):
    if amount <= 0:
        print("余额不足")
    else:
        acct.balance -= amount
def desc(acct):
    return "Account('{name}','{number}',{balance})".format(name=acct.name,number=acct.number,balance=acct.balance)
    
# (2-1) 定义__init__方法:在Python中,对象方法的第一个参数一定是对象本身
class Amount:
    def __int__(self,name,number,balance):
        self.name=name
        self.number=number
        self.balance=balance
# (2-2)定义__str__()方法
class Account:
    def __str__(self):
        return "Account('{name}','{number}',{balance})".format(name=self.name,number=self.number,balance=self.balance)
        
# (3)定义内部属性:如果想要避免用户字节的误用,那么可以使用self.__XXX的方法定义内部值域
class Account:
    def __int__(self,name,number,balance):
        self.__name=name
        self.__numner=number
        self.__balance=balance
# (4)定义外部属性:可以考虑在这类方法上加注@property
class Account:
    def __int__(self,name,number,balance):
        self.__name=name
        self.__numner=number
        self.__balance=balance
    @property
    def name(self):
        return self.__name
# (5)静态方法与类方法
# 标注 @staticmethod:虽然可以通过实例来调用@staticmethod标注,但是建议通过类名来调用,明确让类名称作为静态方法的命名空间
class Accoutn:
    @staticmethod
    def default(name,number):
        return Acount(name,number,100)
# 标注@classmethod:类中的方法如果标注了@classmethod,那么第一个参数一定是接受所在类的type实例
class Account:
    @classmethod
    def default(clz,name,number):
        return clz(name,numberm,100)
        
# (6)定义运算符
class Rational:
    def __init__(self,numer,denom):
        self.numer=numer
        self.denom=denom
    def __add__(self, other):
        return Rational(self.numer*other.denom+other.numer*self.denom,self.denom*other.denom)
    def __sub__(self, other):
        return Rational(self.numer*other.denom-other.numer*self.denom,self.denom*other.denom)
    def __mul__(self, other):
        return Rational(self.numer*other.numer,self.denom*other.denom)
    def __truediv__(self, other):
        return Rational(self.numer * other.denom, self.denom * other.denom)
    def __str__(self):
        return '{numer}/{denom}'.format(numer=self.numer,denom=self.denom)
    def __repr__(self):
        return 'Rational({numer},{denom})'.format(numer=self.numer,denom=self.denom)
r1=Rational(1,2)
r2=Rational(2,3)
print(r1+r2)
print(r1-r2)
print(r1*r2)
print(r1/r2)

# (7)__new__(), __init__(),__del__()
# __init__()是在类的实例构建之后进行初始化的方法,类的实例如何构建实际上是由__new__()来定义。
# __new__()方法的第一个参数是类本身,之后可定义任何参数作为构建对象之用。
# __new__()方法可以返回对象,如果返回的对象是第一个参数的类实例,接下来就会执行__init__()方法,__init__()方法的第一个参数就是__new__()返回的对象。
# __new__()如果没有返回第一个参数的类实例(返回别的实数或None),就不会执行__init__()方法.
class Some:
    def __new__(cls, isClsInstance):
        print("__new__")
        if isClsInstance:
            return object.__new__(cls)
    def __init__(self,isClsInstance):
        print('__init__')
        print(isClsInstance)
Some(True)
Some(False)
# __new__()如果返回第一个参数的类实例,就会执行__init__()方法,借助定义__new__()方法就可以决定如何构建对象与初始化对象,一个应用例子如下:
class Logger:
    __loggers={}    #保存已创建的Logger实例
    def __new__(cls, name):
        if name not in cls.__loggers:   #如果字典中不存在对应的Logger就创建
            logger=object.__new__(cls)
            cls.__loggers[name]=logger
            return logger
        return cls.__loggers[name] #否则返回字典中对应的Logger实例
    def __init__(self,name):
        #为了不重复设置Logger实例属性,使用vars(self)获取Logger实例上的属性列表
        if name not in vars(self):
            self.name=name #设置Logger的名称
    def log(self,message):  #简单模拟日志的行为
        print('{name}:{message}'.format(name=self.name,message=message))
logger1=Logger('xlogging')
logger1.log('一些日志信息')
logger2=Logger('xlogging')
logger2.log('另外一些日志信息')
logger3=Logger('xlog')
logger3.log('再来一些日志信息')
print(logger1==logger2)
print(logger2==logger3)
# 如果想在对象被删除时自行定义一些清楚相关资源的操作,可以做执行__del__()方法
class Some:
    def __del__(self):
        print('__del__')
s=Some()
s=None
# (1)定义类:在PPython中可以使用class来创建一个专门类
class Acount:
    pass
def account(name,number,balance):
    aact=Acount()
    aact.name=name
    aact.number=number
    acct.balance=balance
    return aact
def deposit(acct,amount):
    if amount <= 0:
        print("存款金额不得为负")
    else:
        acct.balance +=amount
def withdrow(acct,amount):
    if amount <= 0:
        print("余额不足")
    else:
        acct.balance -= amount
def desc(acct):
    return "Account('{name}','{number}',{balance})".format(name=acct.name,number=acct.number,balance=acct.balance)
    
# (2-1) 定义__init__方法:在Python中,对象方法的第一个参数一定是对象本身
class Amount:
    def __int__(self,name,number,balance):
        self.name=name
        self.number=number
        self.balance=balance
# (2-2)定义__str__()方法
class Account:
    def __str__(self):
        return "Account('{name}','{number}',{balance})".format(name=self.name,number=self.number,balance=self.balance)
        
# (3)定义内部属性:如果想要避免用户字节的误用,那么可以使用self.__XXX的方法定义内部值域
class Account:
    def __int__(self,name,number,balance):
        self.__name=name
        self.__numner=number
        self.__balance=balance
# (4)定义外部属性:可以考虑在这类方法上加注@property
class Account:
    def __int__(self,name,number,balance):
        self.__name=name
        self.__numner=number
        self.__balance=balance
    @property
    def name(self):
        return self.__name
# (5)静态方法与类方法
# 标注 @staticmethod:虽然可以通过实例来调用@staticmethod标注,但是建议通过类名来调用,明确让类名称作为静态方法的命名空间
class Accoutn:
    @staticmethod
    def default(name,number):
        return Acount(name,number,100)
# 标注@classmethod:类中的方法如果标注了@classmethod,那么第一个参数一定是接受所在类的type实例
class Account:
    @classmethod
    def default(clz,name,number):
        return clz(name,numberm,100)
        
# (6)定义运算符
class Rational:
    def __init__(self,numer,denom):
        self.numer=numer
        self.denom=denom
    def __add__(self, other):
        return Rational(self.numer*other.denom+other.numer*self.denom,self.denom*other.denom)
    def __sub__(self, other):
        return Rational(self.numer*other.denom-other.numer*self.denom,self.denom*other.denom)
    def __mul__(self, other):
        return Rational(self.numer*other.numer,self.denom*other.denom)
    def __truediv__(self, other):
        return Rational(self.numer * other.denom, self.denom * other.denom)
    def __str__(self):
        return '{numer}/{denom}'.format(numer=self.numer,denom=self.denom)
    def __repr__(self):
        return 'Rational({numer},{denom})'.format(numer=self.numer,denom=self.denom)
r1=Rational(1,2)
r2=Rational(2,3)
print(r1+r2)
print(r1-r2)
print(r1*r2)
print(r1/r2)

# (7)__new__(), __init__(),__del__()
# __init__()是在类的实例构建之后进行初始化的方法,类的实例如何构建实际上是由__new__()来定义。
# __new__()方法的第一个参数是类本身,之后可定义任何参数作为构建对象之用。
# __new__()方法可以返回对象,如果返回的对象是第一个参数的类实例,接下来就会执行__init__()方法,__init__()方法的第一个参数就是__new__()返回的对象。
# __new__()如果没有返回第一个参数的类实例(返回别的实数或None),就不会执行__init__()方法.
class Some:
    def __new__(cls, isClsInstance):
        print("__new__")
        if isClsInstance:
            return object.__new__(cls)
    def __init__(self,isClsInstance):
        print('__init__')
        print(isClsInstance)
Some(True)
Some(False)
# __new__()如果返回第一个参数的类实例,就会执行__init__()方法,借助定义__new__()方法就可以决定如何构建对象与初始化对象,一个应用例子如下:
class Logger:
    __loggers={}    #保存已创建的Logger实例
    def __new__(cls, name):
        if name not in cls.__loggers:   #如果字典中不存在对应的Logger就创建
            logger=object.__new__(cls)
            cls.__loggers[name]=logger
            return logger
        return cls.__loggers[name] #否则返回字典中对应的Logger实例
    def __init__(self,name):
        #为了不重复设置Logger实例属性,使用vars(self)获取Logger实例上的属性列表
        if name not in vars(self):
            self.name=name #设置Logger的名称
    def log(self,message):  #简单模拟日志的行为
        print('{name}:{message}'.format(name=self.name,message=message))
logger1=Logger('xlogging')
logger1.log('一些日志信息')
logger2=Logger('xlogging')
logger2.log('另外一些日志信息')
logger3=Logger('xlog')
logger3.log('再来一些日志信息')
print(logger1==logger2)
print(logger2==logger3)
# 如果想在对象被删除时自行定义一些清楚相关资源的操作,可以做执行__del__()方法
class Some:
    def __del__(self):
        print('__del__')
s=Some()
s=None