Classes and methods in Python object-oriented programming

Source: Internet
Author: User
Classes and class methods are essential features of object-oriented programming languages. This article summarizes the learning notes about classes and methods in Python object-oriented programming. For more information, see Class and instance

Python is an object-oriented language, and the most important concept of object-oriented is classes and instances. I remember that I didn't quite understand these concepts when I first learned them until the teacher said "things are clustered ". yes, it's a class.

Similar things

Class is actually to classify things with the same features into a class, such as a person

class Person(object):  pass

We have defined the human class, but people have some characteristics, such as two eyes and one mouth. we add these to it.

class Person(object):  eyes = 2  mouth = 1

Some people's information has been written into it, but there are still people with names, such as me mink. well, I can't treat myself badly. I have to add these to it.

class Person(object):  eyes = 2  mouth = 1  name = mink

It's perfect. a person has finally finished it. after a day, I spent one minute (joking). let's read the information. human beings have two eyes, one mouth, and the other name is mink. --! A little wrong. mink is my name ~ Why is it mink?
Mink is the name of a human being. it is obviously wrong that the name of a human being is mink. "wo" should be an individual human being and a single example.

class Person(object):  eyes = 2  mouth = 1    def __init__(self, name):    self.name = name me = Person('mink')

Now I have my own name instead of sharing it with everyone. this method is called an instance, but I have a skill that no one else can use. I am not affected by gravity.

Class Person (object): eyes = 2 mouth = 1 def _ init _ (self, name) self. name = name def jineng (self, txt): print "% s" % (self. name, txt) me = Person ('mink') me. jineng ("I am not affected by gravity, I will fly ")

Class method and static method
In python, you can often see @ classmethod and @ staticmethod, which are called class methods and instance methods.

class Animal(object):  name = 'lili'  age = 1cat = Animal()print cat.name, cat.age   # print 'lili' 1

An Animal class is created, a cat instance is generated, and the cat name and age are printed. the returned result is the attributes of the Animal class, that is, the instance accessesAttribute

# Print cat with the same content. name, cat. ageprint Animal. name, Animal. age adds a method (function) class Animal (object): name = 'Lili' age = 1 def edit (self, name, age): self to the Animal class. name = name self. age = agecat = Animal () cat. edit ('rol', 2) print cat. name, cat. age # print 'rol' 2 print Animal. name, Animal. age # print 'Lili' 1

That is to say, the default method is an instance method. the instance method modifies the attributes of the instance, but the attributes of the class are not changed.

# Modify this function def edit (self, name, age): name = name self. age = agecat = Animal () cat. edit ('rol', 2) print cat. name, cat. age # pirnt 'rol' 2 print Animal. name, cat. age # print 'Lili' 1

It indicates that the instance method cannot modify the class attributes, but what should I do if I want to modify the class attributes?

# Modify edit @ classmethoddef edit (cls, name, age) again: cls. name = name cls. age = agecat = Animal () cat. edit ('rol', 2) print cat. name, cat. age # print 'rol' 2 print Animal. name, Animal. age # print 'rol' 2

Note that the first parameter of the edit function has changed self to cls. in python, we recommend that you use cls in the class method and the parameter of the instance method is self, in addition, the class method (function) that can be used for the instance is described here)
So I am adding the init method to this class to initialize the attribute.

class Animal(object):  name = 'lili'  age = 1  def __init__(self, name, age):    self.name = name    self.age = age  ...cat = Animal('kuku', 4)cat.edit('rol', 2)print cat.name, cat.age     # print 'kuku' 4print Animal.name, Animal.age  # print 'rol' 2

After _ init _ is added, cat no longer uses the class attributes, but the edit method does not change the attributes of the cat instance.

# Add staticmethod @ staticmethoddef say_name (name = None): if not name: name = self. name print 'My name is % s. '% namecat = Animal ('Kaka', 3) cat. say_name () # NameError: global name 'self 'is not defined # is the self field not added to say_name (self, name = None) not found) :... cat. say_name () # TypeError: say_name () takes at least 1 argument (0 given), the parameter is missing

This indicates that staticmethod cannot use instance attributes and methods, and of course it cannot use classes.

# Modify the code # first create an instance method, which uses the staticmethod @ staticmethoddef say_name (name): print 'My name is % s. '% namedef say (self): self. say_name (self. name) @ classmethoddef _ say (cls): cls. say_name (cls. name) cat = Animal ('Kaka ', 3) cat. say () cat. _ say ()

Staticmethod can be accessed through the class method and instance method.
Summary:
Static method)

Static methods cannot use instance attributes and methods

Static methods cannot use class attributes and methods.

Static methods can be called through classes or instances.

The static method is equivalent to the global function of the scope in the class.

Classmethod)

Class methods can use class attributes and methods

Class methods can use static methods

Class methods can be called through classes or instances.


For more articles about classes and methods in Python object-oriented programming, please follow the PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.