Understanding Python in one article (6) -----Classes and Objects

Today I will introduce the " object " to everyone . As we all know, Python is an object-oriented programming language. A large part of the reason why Python is so powerful is that there are objects everywhere in Python. It can be seen that one of the keys to learning Python is to learn classes and objects. it is good! Step into the topic.

1. What is a class and what is an object

  • Definition of
    a class A class includes:
    • 1. Attributes, which describe the static properties of the class
    • 2. Method, which describes the action of the class-the definition of the object
  • The definition of
    an object An instance of a data structure defined by a class, so it is also called an instance object.
  • Small case
# 定义一个学生类
class Stu:
    numid = 2020000078
    name = 'djk'
    gender = 1
    def Print(self):
        print('我是一个学生!')
# 实例化一个对象stu
stu = Stu()
stu.Print()

Second, how to define the class

class Stu:
    def __init__(self,numid,name,gender,loc):
        self.numid = numid
        self.name = name
        self.gender = gender
        self.loc = loc
    def Print(self):
        print(self.numid,self.name,self.gender,self.loc)
# 实例化
stu = Stu(1,'djk',1,'shandong')
# 调用Print()函数
stu.Print()

As for why there is a self here, you can read another article of mine. It explains it very clearly, so I won’t introduce it in detail here, and I can also understand self by comparing it with the Java language. Deeply understand the self parameter and __init__(self) method in Python-by analogy to the Java language

Three, the three characteristics of object-oriented

3.1 Packaging

Object is a encapsulation, encapsulating the attributes and methods belonging to the object into a class, and only allowing the object itself to access internally!

3.2 Inheritance

  • Inheritance is a mechanism by which subclasses automatically share data and methods between parent classes
  • Case study
class Parent:
    def Hello(self):
        print('正在调用父类的方法')
class Child(Parent):
    pass
p = Parent()
p.Hello()
c = Child()
c.Hello()

Insert picture description here

  • If the subclass defines methods and properties with the same name as the parent class, it will automatically override the properties and methods corresponding to the parent class
  • Case study
class Parent:
    def Hello(self):
        print('正在调用父类的方法')
class Child(Parent):
    def Hello(self):
        print('正在调用子类的方法')
p = Parent()
p.Hello()
c = Child()
c.Hello()

Insert picture description here

3.3 Polymorphism

  • What is polymorphism?
    Polymorphism means that the method name is the same, but the method is implemented in a different way
  • Case study
# 多态案例
class A():
    def fun(self):
        print('我是小A')
class B():
    def fun(self):
        print('我是小B')
a = A()
a.fun()
b = B()
b.fun()

Insert picture description here

4. What is public and what is private

  • There are two attributes of member variables in class Class: instance attributes and class attributes.

  • Instance attributes are defined in the constructor (__init__), prefixed with self when they are defined.

  • Class attributes are attributes defined outside of methods in the class but in the class. Class attributes are shared among all instances. Both inside and outside the class can be accessed through the "class. class attribute".

Two forms of access: In the main program, the instance attributes can only be accessed through the object name; while the class attributes can be accessed through the class name or the object name.

  • For public members (methods and variables), they can be used publicly, both inside and outside the class.

  • For private members (methods and variables), they can only be used inside the class, but they can also be accessed through special methods, namely "object name._class name + private member", book._Book__types.

    • Two forms of expression: When defining a class attribute, if it starts with two short underscores "__", it means it is a private attribute, otherwise it is a public attribute. For example, self. size = s is a private attribute, and self.price = money is a public attribute.
      Private method: start with two underscores "
      " and cannot be called directly by the object name. It can only be called by self in methods belonging to the object. For example, self._namemethod
  • Public method: call directly by the object name. For example, a.printLcs

  • Static method: It can be called by the class name and object name, but it cannot directly access the members belonging to the object, only the members belonging to the class.

Five, some related BIF

Method name Method introduction
issubclass(class,classinfo) If class is a subclass of classinfo, return True
isinstance(object,classinfo) Check whether an instance object object belongs to the classinfo class
hasattr(object,name) Test whether an object has the specified attribute name
getattr(object,name[,default]) Return the attribute value specified by the object. If the attribute does not exist, if the default is set, the default will be printed out; otherwise, an AttributeError will be thrown
setattr(object,name,value) Set the value of the specified attribute in the object. If the specified attribute does not exist, a new attribute will be created and assigned a value
delattr(object,name) Delete the specified attribute in the object; if the specified attribute no longer exists, an AttributeError exception will be thrown
property(fget = None,fset = None,fdel = None,fdoc = None) Set attributes with self-defined attributes

Six, the relationship between class, class object and instance object

class C:
    count = 0
a = C()
b = C()
c = C()
print('a修改之前:{}'.format(a.count))
print('b修改之前:{}'.format(b.count))
print('c修改之前:{}'.format(c.count))
c.count += 10 # 修改的是实例对象c
print('c修改实例对象之后:{}'.format(c.count))
# 我们修改类对象
C.count += 100
print('a修改之后:{}'.format(a.count))
print('a修改之后:{}'.format(b.count))
print('c修改类对象之后:{}'.format(c.count))
# 为什么会这样呢?因为实例属性将类属性给覆盖了,我们只能看到实例属性,不能看到类属性

Guess you like

Origin blog.csdn.net/dongjinkun/article/details/113739258