Home  >  Article  >  Backend Development  >  About classes and methods in Python object-oriented programming

About classes and methods in Python object-oriented programming

高洛峰
高洛峰Original
2017-03-01 13:33:381388browse

Classes and instances

Python is an object-oriented language, and the most important concepts of object-oriented are classes and instances. I remember that I didn’t understand these very well when I first learned it. Concept, until the teacher said "birds of a feather flock together". That's right, it's a class. Classification

birds of a feather flock together

A class actually means grouping things with the same characteristics into one category. For example, human

class Person(object):
  pass

We have defined the class human, but human has some characteristics, such as two eyes and a mouth, we add these in

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

I have already written some information about the person, but the person still has a name, such as me mink. Well, I can’t treat myself badly, I have to add these in

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

It’s so perfect, one person finally finished it. God took me a day and I took a minute (just kidding), let’s read the message. Human being There are two eyes, one mouth, and the name is mink. - -! Something is wrong, mink is my name~ Why are humans called mink?
mink is the name of humans. It is obviously wrong for humans to be named mink. , "wo" should be a human individual, a single example

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

me = Person('mink')

Now I finally have my own name instead of sharing it with everyone, this method is called instance But I have a skill that others don’t have, 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 %s" % (self.name, txt)

me = Person('mink')
me.jineng("我不受重力影响, 我会飞")

##Class methods and static methods
python You can often see @classmethod and @staticmethod, which are called class methods and instance methods.

class Animal(object):
  name = 'lili'
  age = 1

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

Created an animal class and generated a cat Instance, print cat's name and age, you can see that what is returned is the attribute of Animal class, that is, the instance accesses the

attribute of the class

# 显示内容是一样的
print cat.name, cat.age
print Animal.name, Animal.age
给Animal类添加一个方法(函数)

class Animal(object):
  name = 'lili'
  age = 1

  def edit(self, name, age):
    self.name = name
    self.age = age

cat = 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, this method added by default is an instance method. The instance method modifies the attributes of the instance, but the attributes of the class do not change

# 我们修改一下这个函数
def edit(self, name, age):
  name = name
  self.age = age

cat = Animal()
cat.edit('rol', 2)

print cat.name, cat.age     # pirnt 'rol' 2
print Animal.name, cat.age   # print 'lili' 1

Explain that instance methods cannot modify the attributes of the class, but what should I do if I want to modify the attributes of the class?

# 再一次修改edit
@classmethod
def edit(cls, name, age):
  cls.name = name
  cls.age = age

cat = Animal()
cat.edit('rol', 2)

print cat.name, cat.age     # print 'rol' 2
print Animal.name, Animal.age  # print 'rol' 2

What needs to be noted here is the first parameter of the edit function Self becomes cls. In python, it is recommended that you use cls in class methods and the parameter of instance method is self, and it is explained here that instances can use class methods (functions)

Then I am adding an init method to this class To initialize the attributes

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' 4
print Animal.name, Animal.age  # print 'rol' 2

After adding __init__, cat no longer uses the attributes of the class, and modifying the edit method does not change the attributes of the cat instance.

# 添加staticmethod
@staticmethod
def say_name(name=None):
  if not name:
    name = self.name
  print 'my name is %s.' % name

cat = Animal('kaka', 3)
cat.say_name()        
# 运行的话会报 NameError: global name 'self' is not defined  
# 那是不是没给他添加self字段, 所以没找到
def say_name(self, name=None):
  ...

cat.say_name()
# TypeError: say_name() takes at least 1 argument(0 given), 显示缺少参数

This means that staticmethod cannot use the attributes and methods of instances, and of course it cannot use classes. Then the reverse is true

# 我们修改一下代码
# 先创建一个实例的方法, 他使用类的staticmethod

@staticmethod
def say_name(name):
  print 'my name is %s.' % name

def say(self):
  self.say_name(self.name)
  
@classmethod
def _say(cls):
  cls.say_name(cls.name)

cat = Animal('kaka', 3)
cat.say()
cat._say()

staticmethod can be accessed through class methods and instance methods.


To summarize:
static method (staticmethod)

Static methods cannot use instances. Properties and methods

Static methods cannot use the properties and methods of the class

Static methods can be called through classes or instances

Static methods are equal to global functions with scope in the class

Class method (classmethod)

Class method can use the attributes and methods of the class

Class method can use static method

Class method can use the class Or instance call


#For more articles about classes and methods in Python object-oriented programming, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn