Holiday idle come to nothing, pick up Python to see again, a little harvest, recorded as follows.
First, Python has the difference between function and method, from types. Methodtype and Types.functiontype can be seen, the difference is that method is a function in class, but can only be called methods;
Second, Python is a dynamic language, the Duck type: As long as it looks like a duck and behaves like a duck, it is considered a duck. This is Python polymorphism, which is significantly different from Java.
Python also has the distinction between class and instance: The former is abstract and the latter is an instance.
Unlike Java, Python supports dynamic addition of attributes (values or methods/functions, values have no say, here we only discuss functions/methods): You can add attributes to instance (for the current object only), or you can add attributes to the class (available for all objects)!
Take class student as an example:
class Student (object): Pass
Adding a method to the student class itself is simple, just define a method and assign it to the Student property! The only thing to remember is that the first argument of a method must be self. As follows:
def Set_age (self, Age): == set_age # so you can! = Student () stu.set_age () Print # Here we get
Adding a property method to student's instance is cumbersome, and you need to turn the defined function into Methodtype, and then give the instance property of student. Similarly, the first argument of a method must be self. As follows:
Import Types def set_name (self, name): == Student ()# stu.set_name = set_name # DONT# must be like this Stu.set_name ('larryzeal')print(stu.name)
As to why it must be turned into methodtype, it can be explained by executing the code that is commented out above:
Import Types def set_name (self, name): ==# DONTstu.set_name ('larryzeal' # error! don't know what self is. Print (Stu.name)
That is, the function is called directly, not by method. Personally, the difference is that Self:class will actively bind objects to self, others will not!
According to this conjecture, you can actually output the type of the properties of the above two cases:
Print (Type (stu.set_name))
One is method, one is function!
Python Learning Summary