A deep understanding of Python classes

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qq_29027865/article/details/89844083


Here Insert Picture Description

Class definition

The most basic role is to package the class, the class is only responsible to define, to portray something.
Type the first letter to uppercase, lowercase name of the variable;
between two word variables with an underscore to connect, such as: student_number, but the class is not intended to underscore the connection: StudentHomework;

example:

class Student():
    name = ''
    age = 0
    # 类中的方法的参数必须加self
    def print_file(self):
        print('name:' + self.name)
        print('age:' + str(self.age))

# 要想使用这个类,就需要先对类进行实例化
student = Student()
# 调用类下面的方法
student.print_file()

Examples of calling method and class went below do not define a class in a module below, went to completion class: Note. If you write the class module, then this module will write only classes, and instantiate and use of the class to go on another module, and then in another module from ... import ... by introducing the class to instantiate

Difference function and method

Is a title on the design level, the function is run, procedural title;
definition in the class, called methods appropriate because object-oriented class is the basic concept, is oriented design. Defined in the module process, referred to as appropriate function;
variables in the module, is defined as a variable; the variable defined in the class, is generally referred to as data members, in order to reflect the data members of the class of the package, each of the variables are considered as a class of data, such data is used to describe the characteristics of the class;

Classes and Objects

What classes and objects in the end is what kind of relationship there between them?
And classes of objects are linked together by way of example, the class is the real world or thought world entities reflected in the computer, it will operate on the data (data members) and the data (methods) packaged together, i.e., class It is used to characterize some of the basic characteristics of things.
The reason for that is the object-oriented world of the computer in order to put some things in the real world are mapped to your computer.
We use data to describe the members of some of the features of things, a way to describe the behavior of some things. For example, students in the class, the student's name and age are features, homework, school is the behavior.
Class design is good or bad behavior and characteristics you how to define the behavior to the corresponding body design.
Class is an abstract concept, is a general term for a class of things, not specific. While showing a specific thing that is the object class just tell us what this type of thing in features, but the specific characteristics of what values need to be done by instantiating. When the class is instantiated, it becomes a specific object. Class can be understood as a template by the template, you can create different objects.

Constructor

Examples of the class is to use a template to create a new object, then the object is how to make the same template instantiation not it? Analogy at the function, we have different definitions of the function parameter and then pass different arguments to intrinsic function, which allows the function returns a different result.
So the class, we also need to pass it different parameters in order to instantiate an object not the same, whether we can directly when instantiating was introduced to it:

Student = Student(name = 'wjp',age = 18)

This is clearly not enough, then we need to define a class of 'special' functions in:

class Student():
    name = ''
    age = 0
    def __init__(self,name,age):
        # 构造函数
        # 初始化对象的属性
        self.name = name
        self.age = age 
    def do_homework(self):
        print('homework')
student1 = Student('石敢当',18)
print(student1.name)

When used to instantiate an object class, py will automatically call the constructor, we can explicitly to invoke the constructor. Call the constructor display returns none.
The role of the constructor is to make your class template instantiation different objects , __ init__ formal parameter defines which parameters, which parameters will then pass the class instantiation.

Distinguishing module variables and class variables

Analog module at the global and local variables, within the scope of local variables, so the value of the local variable does not change the global variables.
But if you understand for class, equivalent to a local variable, it would be wrong. The module can not be global variables and functions of the module local variables is equivalent to a class class variables and instance variables .

Instance variables and class variables

Class variables and class is related to variables, instance variables are associated together and objects, and objects are created out of a class template.
In addition to the methods defined in class variables, called a class variables, instance variables to hold is variable by self. Characteristic value instance variable name.

student1 = Student('石敢当',18)
student2 = Student('喜小乐',19)
# 实例变量
print(student1.name)
print(student2.name)
# 类变量
print(Student.name)

So the definition of class variables what is it? We have to consider the issue from the perspective of object-oriented, object-oriented computer is a map of the real world of relationships. Class is abstract, the object is specific, so the name and age is defined as two variables is not suitable class variables, instance variables should be defined and associated objects.
(Some from the real world point of view to consider, why have class, why have class variables, Why should object.)
To give an example to illustrate the role of the class variable and when to use a class variable:

class Student():
    sum = 0

Object-oriented is an abstract concept, there is a need for abstract thinking ability, and can be used repeatedly in practice, to a deep understanding.

Variable classes and objects to find order

Here's the problem, is also a top class, I want to output instance variables, but now is what kind of output variables is it?

class Student():
    name = ''
    age = 0
    def __init__(self,name,age):
        name = name
        age = age
student1 = Student('石敢当',18)
# 想打印实例变量
print(student1.name)
# 想打印类变量
print(Student.name)

So the question is why? We use __dict__ to Print all the relevant variables under this object, get an empty dictionary, plus a self assigned to the case, the dictionary under variable objects have instance variables. So for instance variable output, in essence, is null, then why not output none, while the output class variables?
So here it leads to the mechanism py find related variables: If we try to access the instance variables, then py is first in the list of objects in instance variables to find there a name of the variable. If not, py and does not return an empty, it will continue to variables in the class to look for.
(If you did not find the class variable, and there is inheritance, then we will continue to traverse the parent class to look for.)

Examples of the method and self

Question one:

class Student():
    name = 'wjp'
    age = 23
    def __init__(self,name,age):
        self.name = name
        self.age = age
        print(age)
        print(name)

Second problem:
In the instance method, whether access to the class variables?

When defining instance methods, the first parameter to define self, but in reference to an instance method, py will help us to automatically call the self (do not need to explicitly specified). Similarly, when the definition may be practiced without self, this can be an alternative, as will be appreciated in the Zen py implicit rather than explicit.
self is the current target of a call to a method, and only self-related objects, and classes are not related.

def __init__(this,name,age):
    this.name = name

Analogy instance variables and instance methods:
instance variables are variables defined objects associated, and an instance method is associated with an instance of an object, you can call the instance method called instance methods. ( Instance method biggest feature is its parameters need to pass a Self )

Access instance variables and class variables in the example method

What is the relationship between the variables of

From the object-oriented perspective, the method represents a class of behavior, and the variable represents characterizes a class. In most cases, the method needs to do some arithmetic variable, and ultimately to a change in state variables.

In an instance method if you can access the class variables?

Pre-knowledge review

Examples of methods main function, is used to describe the class behavior , acting constructor is used to initialize the various classes of features .
In the instance method, self.name and name are equivalent? self.name read is the instance variable , the name is read parameter to name .
__Dict__ be viewed by magic function method uses the object, but only for external calls class can only be output correctly during external calls, internal can not. Such as:

class Student():
    name = ''
    def __init__(self,name1,age):
        self.name = name1
        self.age = age
        print(self.name)
        print(self.__dict__)
        # 下面这句报错
        print(name)

A first method example method to access variables

How to access our review method to the class variable outside the class, when accessed externally, through our class. Class variable name to access the class variables. So, too, when internal access is through the class. Class variable names for a visit.

The second way to access variables in an instance method

Self. class . Class variable names

class Student():
    sum1 = 0
    def __init__(self, name, age):
        self.name = name 
        self.age = age
        print(self.__class__.sum1)

It must be clear rationale class variables, instance variables, an example method a pattern cross call between them.

Class Methods

Why is there a class method, and class methods, what kind of role;
different two class methods and instance methods:

  1. Examples of the method requires parameters define self, define a class method requires parameters CLS; (it does not matter in fact, a different name)
  2. @Classmethod need to add pre class methods;
  3. Examples of methods concerned with things objects, class methods concerned with the thing itself;
   class Student:
   sum = 0
   def __init__(self):
        pass
   def do_homework(self):
      print('homework')
   @classmethod
   def plus_sum(cls):
      cls.sum += 1
      print(cls.sum)d
# 类方法的调用

# 既然是类方法,调用时就和类相关,和对象是没有太大关系的;

Student.plus_sum()

The main role of class and method of operating a number of variables associated with the class, then there are two problems:

  1. Since it can operate in an instance method in class variables, class methods to do so also?
  2. You can use a class to call the class method, then the possibility of using objects to call the class method?
    1-> is to and the corresponding abstract class class method to do so treated;
    2-> Py may use the class object to call the method, there are limitations in other languages;

Static method

@staticmethod
def add(x,y):
	# 静态方法访问类变量
    print(Student.sum)
    # 静态方法访问实例变量
    print(name)

Static and instance methods, class of different methods:

  1. Unlike the static method and class methods instance method has a mandatory 'keyword': class method cls represents the class itself, example of a method of self represents the object itself;
  2. There @staticmethod top decorator;

Static methods and object-oriented very weak correlation, generally not recommended;

Visibility members

Understood as members: variables and methods, its visibility is the visibility of the following variables and methods py object.
For members, we have two ways to access external access to internal and, in fact, when used, for instance variables to be operated by a method, rather than directly modified because variables can be modified within the method.

# 想对score赋值,定义方法
def marking(self,score):
	if score < 0:
    	return '不能够给别人打负分'
    self.score = score
    print(self.name + '同学本次考试分数为:' + str(self.score))

Private methods

Modified value based on the following variables to be accomplished by the method, and can not be modified directly.
So py how to define private or public property members, to directly modify its operation to prevent it?
py defined, when there are former members of the double-underlined when, on the definition of the members are private, can not be called externally.
Such as:

# 私有方法
def __marking(self,score):
	pass

Why a double underscore in front of the constructor __init__, but it is not private?
In this way both before and after the underscore is actually a custom function py naming rule that magic function, as members of the public visibility, such as:

def __marking__(self,score):
	pass

Private variables

Above we said that the definition of private methods, and for the private variables, strictly speaking, py is no private variables. Let's look at an example:

class Student():
	def __init__(self):
    	self.__score = __score

However, in practical operation, we will set the method as private, private method is not accessible, but after the variable is set to private, but variables can be accessed and evaluated, which is what causes it?

Such as:

class Student():
    def __init__(self):
        self.__score = 0
    def marking(self, score):
        self.__score = score
        print(self.__score)
student1 = Student('大鹏',23)
student1.marking(100)
student1.__score = 666
print(student1.__score)

student2 = Student('小菜',23)
print(student2.__score)
--- 
大鹏的成绩是100
666
报错....

Here we will direct the private variables __score been modified to 666, then the private property what? Why can directly modify it?
In fact, here we see has been able to modify the 'illusion', according to the characteristics py dynamic languages, where student .__ score essentially created a new variable __score, then subjected to print. The py private variables in the mechanism, in essence, is a double underscore defined variables had a new name: the name of the class _ __ private variable name, it will not directly access access to the private variable names.

Class inheritance

The most basic definition of inheritance is to avoid repetition we define methods and repeated variables.
In py, the inherited certain way is to write in their brackets on the parent class, such as:

class Human():
	pass
class Student(People):
	pass

Next, in succession when considering the need to consider the characteristics subclass of Student class, its name, age not specific features, so it can be placed in the parent class, py can allow multiple inheritance principle, a parent you can have multiple sub-classes:

class Human():
	def __init__(self,name,age):
    	self.name = name
        self.age = age
class Student(Human):
	def __init(self,school,name,age):
    	self.school = school
        # 掉用父类的初始化方法一:
        # 此处要加self:因为其和实例化时去调用构造函数是不一样
        # 通过对象来调用实例方法时,其self知道这个对象,而通		 # 过类来调用时,其实例方法需要指明self;
        Human.__init__(self, name, age)
        # 方法二:
        super(Student, self).__init__(name, age)
	def do_homework(self):
    	pass
student = Student('阿里','大鹏',23)
print(student.name)

Guess you like

Origin blog.csdn.net/qq_29027865/article/details/89844083