The object-oriented python members, methods, properties, exception handling

A private member of the class

1. What kind of private members?

Private: Only part of meeting the conditions to use

  • Private class attributes
  • The object of private property
  • Private methods

normal status

class B:
    school_name = '老男孩教育'
    def __init__(self,name, sex, age):
        self.name = name
        self.sex = sex
        self.age = age

class A(B): # A的父类是B,这个时候意味着A的实例化对象就可以使用B类中的所有属性或者方法

    class_name = 'python23'

    def func(self):
        print(self.class_name)
        print(self.name)
obj = A() # 实例化一个对象A
print(obj.class_name)
obj.func()# 通过实例化对象来执行A类中的方法
print(obj.school_name)

obj = A('alex', '男', 123)
obj.func() #调用A类中的func方法
print(obj.class_name) # 调用A类中的class_name
print(obj.school_name) # 调用B类中的school_name

What are private members

class A:

    company_name = '老男孩教育'  # 静态变量(静态字段)
    __iphone = '1353333xxxx'  # 私有静态变量(私有静态字段)


    def __init__(self,name,age): #特殊方法

        self.name = name  #对象属性(普通字段)
        self.__age = age  # 私有对象属性(私有普通字段)

    def func1(self):  # 普通方法
        pass

    def __func(self): #私有方法
        print(666)


    @classmethod  # 类方法
    def class_func(cls):
        """ 定义类方法,至少有一个cls参数 """
        print('类方法')

    @staticmethod  #静态方法
    def static_func():
        """ 定义静态方法 ,无默认参数"""
        print('静态方法')

    @property  # 属性
    def prop(self):
        pass

Private static attribute to the class (***)

format

__girlnum = '1个'

  • Objects can not be accessed outside the class, the class can not be accessed externally
  • You can only be accessed from within the class

Internal access method: package into a method and then obj.func () # conscience education

Private members of the class what's the use?

If you want to set some private or do not want to use outside of class, passwords, encryption, etc., can be set to private members

example

# 私有静态属性
class  B:
    school_name = 'OldBoy'

class A(B):
    class_name = 'python23'
    
    _girlnum = '1个' # 我就是私有属性

    
    def func(self):
        # print(self.class_name)
        print(self.__girlnum)
obj = A() 实例化
print(obj.__girlnum) # 对象在类的外部不能访问,类在外部也不能访问print(A.__girlnum),这种就是私有属性
print(obj.func()) # 在类的内部可以访问
从类的外部调用
print(obj.calss_name)
从类的内容部调用
obj.func()

prin(obj.school_name) 对于类的共有静态属性,类的外部,累的内容部,派生类都可调用

3. Set the private property of the object

format:

self.__age = age # Define methods, it becomes a private members

obj.func()Call the method

  • Outside the class is not accessible
  • Class may be used in internal
class  B:

    def __init__(self, name, age)
            self.name = name
            self.__age = age # 这就变成了私有成员了
    def func(self):
            print(self.__age)
            
print(obj.__age)#在类的外部是无法访问的
obj.func()# 在类的内部可以使用


#派生类
既想用子类也想用父类用super
子类打印父类属性,派生类中也不能访问

4. expand private members

In addition to internal private members of the class you can not really access it?

class A:
        __girl_num = '1个'

print(A._dict_)
# 输出结果
'_A__girlnum'

print(A.__A_girlnum) # 这样是可以访问的,千万不要去访问

python all private members, is in front of the private members plus __ class name it. So is accessible

Second, class methods and static methods

The method uses the class @classmethod

  • The method of an object is modified to bind a class method
  • In the method of course you can reference any static class variable
  • You can not instantiate an object, you use the class name to call this method directly outside

How to use a class method? (***)

Definition methods: @classmethod cls

Call the method: A.a_func () by using the class name and the object name obj.a_func () call

class A:
        num = 1
    
    def func(self):
        print('实例方法')
    
    # 以下就是类方法
    @classmethod 
    def a_func(cls):
            print(f'cls-->{cls}')
            print('这就是类方法')

# 类方法的调用方法
obj = A()
A.func(obj) # self会得到obj这个对象
A.a_func()# 进行调用

When a class method?

  • Define a method, the self default single pass self is not used
  • And you use this method in the current class name, or are you going to use this kind of memory space in the name of the time
  • That you want to modify the properties of a class before instantiation, you can use this

Example: counting the number of students

class Student:
    count = 0
    def __init__(self, name):
        self.name = name
        self.count1()

    @classmethod
    def count1(cls):
        cls.count += 1

    @classmethod
    def print1(cls):
        return cls.count

ly = Student('李烨')
sq = Student('扫强')
sq1 = Student('扫强')
sq2 = Student('扫强')
sq3 = Student('扫强')
sq4 = Student('扫强')

print(f'学生共计: {Student.print1()}个')

# 输出结果
学生共计: 6个

Static methods (***)

use

Does not depend on the class, nor on the subject, he is a normal function is placed in the class structure is more clear and reasonable.

how to use?

Define a static method: @staticmethod

Call a static method: A.static_func ()

example

class A:
        def func(self):
                print(111)
        @classmethod
        def a_func(cls):
                print(cls)
        @staticmethod
        def static_func(a,b,c): # 也可以传参,就当做一个函数用就行
                print('静态方法')
        
A.static_func() # 类调用静态方法

obj = A()
obj.static_func(1,2,3)

为什么这种函数不写到类的外面?
也用不着类中的内容,但是为了划分,还是要放置于类中,显得与结构更加清晰与合理

切记在函数中要用return的方法返回值进行打印.

Third, the property (camouflage)

use

The method disguised as a property, but it appears reasonable

operty is a special property, performs some function (function) that access and returns the value

The example in question

class Bmi:

    def __init__(self, hight, shoot):
        self.hight = hight
        self.shoot = shoot

    def bmi(self):
        BIM = self.shoot/self.hight**2
        return BIM

obj = Bmi(1.75,67)
print(obj.bmi())

# 输出结果
21.877551020408163

How to use the property?

Camouflage a property: @property

Call a property: obj.bmi executed directly without brackets, from execution method that looks like a property, rather than a method looks

The upper section of the code to disguise, we want bmi disguised as a property

class Bmi:

    def __init__(self, hight, shoot):
        self.hight = hight
        self.shoot = shoot
        
        @property
    def bmi(self):
        BIM = self.shoot/self.hight**2
        return BIM

obj = Bmi(1.75,67)
print(obj.bmi) #不用加括号了
# 输出结果
21.877551020408163

Camouflage property has three @property @ aaa.setter @ aaa.delter

1. 先伪装 obj.bmi()变成obj.bmi @property \n def aaa(self): \n print('get的时候执行我')
2. @aaa.setter  --> def aaa(self,v): \n print('修改的时候执行我') --> obj.aa = '太白' # 结果: 太白 aaa三者必须是一致的
3. @aaa.delter --> def aaa(self): \n print('删除的时候执行我') del Bmi.bmi

Precautions:

  • Set the properties of your object attributes certain properties of the same name can not appear
  • setter, deleter two decorative decorator function can not use return

And the difference between object-oriented function

四、isinstance/issubclass/type

isinstance (a, b): determined by a type b (b derived class) instantiated objects.

Relationship with the object class determination

class A:
        pass
    
class B(A):
        pass

obj = B()
print(isinstance(obj,B))
print(isinstance(obj,A))
# 输出结果
True
True
issubclass (M, N) is determined based M descendant class N
class A:
        pass
    
class B(A):
        pass

class C(B):
print(isinstance(C,B))
print(isinstance(C,A))
# 输出结果
True
True

What type is?

type is a primitive type, a type of data used to determine which class is instantiated objects, python and all are subject in one class is an object, then this is definitely the class object is instantiated by the class out.

python in all classes, as well as most of the list str and so you create these classes are instantiated from the type of the original class come

python inherited object classes are the new class.

but also by the type of the original object class is instantiated come

Fifth, exception handling

What is abnormal

Your program interruption, gains across the board, resulting in your entire project interrupted.

Error type

Grammatical errors

Themselves to avoid, should not appear in your code

logical error

l1 = [1,2,3]
print(l1[4]) #超过了取值范围

Exception handler

  • Exception handling if: shortcomings, nested too much, too complicated, only a simple exception handling
  • With a simple try try

try(***)

From top to bottom to capture the error message, and drainage, but also the role of diversion

Single error is to set up a branch and multi-branch except that a plurality except

Timely resolution of exceptions, to avoid interrupting the program

status_dic = {
    1: 111,
    2: 333,
    3: 444,

}
while 1:
    try:

        num = input('请输入序号')
        int(num)
        print(status_dic[int(num)])

    except KeyError as e:
        print('选项超出范围,重新输入')
    except ValueError as e:
        print('请输入数字')

Universal abnormal

status_dic = {
    1: 111,
    2: 333,
    3: 444,

}
while 1:
    try:

        num = input('请输入序号')
        int(num)
        print(status_dic[int(num)])

    except Exception as e:
            print(e)
print(111)

When to use universal abnormal, when to use a multi-branch?

  • If you just want to dispose of this exception, let the program continue, this time with a universal abnormal
  • If an exception occurs, you want to perform different according to different exception of logic flow, you have to take a multi-branch

Universal multi-branch +

status_dic = {
    1: 111,
    2: 333,
    3: 444,

}
while 1:
    try:

        num = input('请输入序号')
        int(num)
        print(status_dic[int(num)])

    except KeyError as e:
        print('选项超出范围,重新输入')
    except ValueError as e:
        print('请输入数字')
     except Exception:
                pass

Other members of exception handling

status_dic = {
    1: 111,
    2: 333,
    3: 444,

}
while 1:
    try:

        num = input('请输入序号')
        int(num)
        print(status_dic[int(num)])

    except KeyError as e:
        print('选项超出范围,重新输入')
    except Exception:
                pass
# else
status_dic = {
    1: 111,
    2: 333,
    3: 444,

}
while 1:
    try:

        num = input('请输入序号')
        int(num)
        print(status_dic[int(num)])

    except KeyError as e:
        print('选项超出范围,重新输入')
    except Exception:
                pass
        else: # 不出现异常执行,如果出现异常就不执行
                print(666)
# finally
status_dic = {
    1: 111,
    2: 333,
    3: 444,

}
while 1:
    try:

        num = input('请输入序号')
        int(num)
        print(status_dic[int(num)])

    except KeyError as e:
        print('选项超出范围,重新输入')
    except Exception:
                pass
        finally: # 在异常发生之前执行finally
                print('执行finally')

scenes to be used:

  • File Operations

The purpose is before the error, close the file handle

method:

try:

    xxx

    xxx

finally:
      print('哈哈哈哈')
    f.close()
f = open('register', mode='w')
f.write('fdjsaklfd')
f.write('fdjsaklfd')
f.write('fdjsaklfd')
l1 = [1,2,3]
print(l1[1000])
f.write('fdjsaklffjdsklaf')

f.close()

try:
    f = open('register', mode='w')
    f.write('fdjsaklfd')
    f.write('fdjsaklfd')
    f.write('fdjsaklfd')
    l1 = [1, 2, 3]
    print(111)
    print(l1[1000])
    f.write('fdjsaklffjdsklaf')
finally:
    print('哈哈哈哈')
    f.close()
  • Connect to the database engine

finally in the function of

def func():
        try:
                a = 1
                b = 2
                return a + b
        finally:
                print(666)
func()
                

Initiative thrown

Raise Exception('sdfasdf')

Affirmation

assert 条件  # 源码上assert.
assert 1 == 2
print(11)
print(22)
print(33)

Custom exception

TypeError

class Connection(BaseException):

    def __init__(self,msg):
        self.msg = msg


raise Connection('触发了连接异常')
# 异常处理总结:
# 异常处理不能经常使用:异常处理耗费性能.有些错误是需要进行分流使用.代码的可读性变差.
# 关键节点使用.

Guess you like

Origin www.cnblogs.com/zanao/p/11227568.html