GMOEA code running 1--python object-oriented programming

introduction

I was studying the GMOEA paper recently. Although I found the paper and code, the codes are all given in classes. To actually run it, I need to write a script myself. But I am not very familiar with object-oriented programming in python itself. I don’t know the settings of global parameters, as well as parameter transfer and method invocation between test problem objects, etc. Let’s review object-oriented programming in Python first.

Study materials reprinted from Zhihu:

The most comprehensive Python object-oriented programming in history

Concepts shared among classes

It is similar to object-oriented programming languages ​​such as Java, C++, and C#. Python also supports object-oriented programming. There are some common concepts among them.

1. Class: Used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. The objects in it are called instances of the class.
2. Instance: also called object. Through the initialization method defined by the class, it is given a specific value and becomes a "flesh and blood entity".
3. Instantiation: The process or operation of creating an instance of a class.
4. Instance variables: Variables defined in the instance only affect the current instance.
5. Class variables: Class variables are variables common to all instances. Class variables are defined in the class but outside the method body.
6. Data members: the collective name for class variables, instance variables, methods, class methods, static methods and properties, etc.
7. Method: function defined in the class.
8. Static method: A method that can be executed by a class without instantiation
9. Class method: A class method operates on the class itself as an object method.
10. Method rewriting: If the method inherited from the parent class cannot meet the needs of the subclass, the method of the parent class can be rewritten. This process is also called override.
11. Encapsulation: Wrap the internal implementation, make it transparent to the outside, and provide a mechanism for calling the API interface.
12. Inheritance: a derived class (derived class) Inherit the variables and methods of the parent class (base class).
13. Polymorphism: Processed in different ways depending on the type of object.

Class definition and instantiation

import sys
import time
reload(sys)
sys.setdefaultencoding('utf-8')

class studetn:
    # 定义一个类名为studetn
    def __init__(self,idx):
    # 定义初始化构造,这里使用init,还有别的属性比如reversed,iter之类的
        self.idx=idx
        # 初始化变量,方便继承
    def runx(self):
    # 定义运行函数,从上面继承变量
        print self.idx
        # 打印出idx的值,或者做一些别的处理
        time.sleep(1)
a=studetn('a')
a.runx()
# 这是类的调用,一定要记得类的使用方法,首先传入参数,类赋值给一个变量a
# 然后调用这个类下面定义的函数

class method call

instantiation method call

import sys
import time
import requests
reload(sys)
sys.setdefaultencoding('utf-8')

class dd:
    def __init__(self,url):
        self.url=url
    def runx(self):
        print requests.get(self.url).status_code

a = dd('http://www.langzi.fun')
a.runx()
这种调用方法就是实例方法

static method call

Static methods are called directly through the class name, which is equivalent to being globally shared by all objects. Static methods are called by the class and have no default parameters. Remove self from the instance method parameters, and then add the @staticmethod annotation above the method definition to make it a static method. It belongs to the class and has nothing to do with instances. It is recommended to only use class name and static method calling method. (Although it can also be called using instance name and static method)

import sys
import requests
reload(sys)
sys.setdefaultencoding('utf-8')
class ff:
    @staticmethod
    def runx():
        print requests.get('http://www.langzi.fun').status_code
ff.runx()
这里就直接调用了类的变量,只在类中运行而不在实例中运行的方法

class method

The class method is called by the class, using the @classmethod annotation, and passing in at least one cls (referring to the class itself, similar to self) parameter. When a class method is executed, the class calling the method is automatically assigned to cls.

import sys
import requests
reload(sys)
sys.setdefaultencoding('utf-8')
class ff:
    @classmethod
    def runx(cls):
        print requests.get('http://www.langzi.fun').status_code
ff.runx()

Class properties

encapsulation

Encapsulation refers to placing data and implementation code of specific operations inside an object, making them inaccessible from the outside. You must first call the class method to start. From the outside, only one object is visible. The private data and methods inside cannot be seen. Only provides external interfaces.

class cc:
    ccc = 'ccc'
    # cc就是类名 如果想要继承别的类 就class cc(threading) 意思就是从threading继承
    def __init__(self,a,b,c):
        self.a=a
        self.b=b
        self.c=c
print e.ccc
#类变量,在类里面找到定义的变量。
print ccc
# 这里会报错,这就是封装。类中的函数同理。

inherit

When we define a class, we can inherit from an existing class. The new class is called a subclass (Subclass), and the inherited class is called a base class, parent class or super class ( Base class, Super class).
For example, we have written a class named Animal, which has a run() method that can print directly:

class Animal(object):
    def run(self):
        print 'Animal is running...'

When we need to write Dog and Cat classes, we can directly inherit from the Animal class: the inheritance method is to write the parent class into the brackets of the class.

class Dog(Animal):
    pass #表示什么内容也没有
class Cat(Animal):
    pass
dog = Dog()
dog.run()
cat = Cat()
cat.run()

Inheritance can obtain all the functions of the parent class, and then you can override the methods of the parent class and achieve polymorphism.

Polymorphism

The same polymorphic function performs different functions when receiving different objects. It is essentially backward compatible. Generally, the object of the parent class is used as the received parameter, and then when the object of the subclass is input as the parameter, the function of the same name of the subclass can be called. .

Define a function in the parent class that takes the parent class object as input

def run_twice(animal):
    animal.run()
    animal.run()

When we pass in an instance of the parent class object Animal, run_twice() prints out:

run_twice(Animal())
运行结果:
Animal is running...
Animal is running..

When passing in a subclass object

run_twice(Dog())
运行结果:
Dog is running...
Dog is running...

This shows polymorphism.

magic method

My personal feeling is that it is the default method, which is a function that the compiler will fill in for you if you don’t write it.

__init__ :      构造函数,在生成对象时调用
__del__ :       析构函数,释放对象时使用
__repr__ :      打印,转换
__setitem__ :   按照索引赋值
__getitem__:    按照索引获取值
__len__:        获得长度
__cmp__:        比较运算
__call__:       调用
__add__:        加运算
__sub__:        减运算
__mul__:        乘运算
__div__:        除运算
__mod__:        求余运算
__pow__:

Specific use

The constructor init() is automatically triggered when a class is created.

class Foo:
    def __init__(self, name):
        self.name = name
        self.age = 18
obj = Foo(jack') # 自动执行类中的 __init__ 方法

This method is automatically triggered when the destructor del() object memory is released.

class Foo:
    def __del__(self):
        print("我被回收了!")

obj = Foo()
del obj

The output object str() needs to be defined by the user.

class Foo:
    pass
obj = Foo()
print(obj)
定义了__str__()方法后,打印结果是:'jack'class Foo:
    def __str__(self):
        return 'jack'
obj = Foo()
print(obj)

The "Three Musketeers" routines of value acquisition, assignment, and deletion are in Python getitem__(), setitem(), __delitem( ) respectively represent value assignment and deletion. In Python, parentheses after an identifier usually mean executing or calling a method. Adding square brackets [] after the identifier usually represents the meaning of the value

a = 标识符[] :   执行__getitem__方法
标识符[] = a  :   执行__setitem__方法
del 标识符[] :   执行__delitem__方法

class Foo:
    def __getitem__(self, key):
        print('__getitem__',key)
    def __setitem__(self, key, value):
        print('__setitem__',key,value)
    def __delitem__(self, key):
        print('__delitem__',key)
obj = Foo()
result = obj['k1']      # 自动触发执行 __getitem__
obj['k2'] = 'jack'      # 自动触发执行 __setitem__
del obj['k1']             # 自动触发执行 __delitem__

If you need to use for to traverse an object array, you need to define the iterator method iter()

class Foo:
    def __init__(self, sq):
        self.sq = sq
    def __iter__(self):
        return iter(self.sq)
obj = Foo([11,22,33,44])
for i in obj:
    print(i)

If you want to get the object length, you need to override len()

len('ABC')
3
'ABC'.__len__()
3

add__: addition sub: reduction mul : Addition calculation div: Division calculation mod: Find addition calculation __pow: Comparison

These are all arithmetic operation methods, and you need to design specific operation codes for the class yourself. Some Python built-in data types, such as int, have these methods. Python supports operator overloading, that is, rewriting.

class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b
   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)
   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)

As a dynamic language, Python can continue to add any number or any type of variables or methods to a class or object after the class definition and instantiation are completed. This is a characteristic of a dynamic language. For example:

def print_doc(self):
    print("haha")

class Foo:
    pass

obj1 = Foo()
obj2 = Foo()
# 动态添加实例变量
obj1.name = "jack"
obj2.age = 18
# 动态的给类添加实例方法
Foo.show = print_doc
obj1.show()
obj2.show()

What if you want to limit the variables that an instance can add? Slots can be used to restrict instance variables, for example, only allowing instances of Foo to add name and age attributes.

def print_doc(self):
    print("haha")
class Foo:
    __slots__ = ("name", "age")
    pass
obj1 = Foo()
obj2 = Foo()
# 动态添加实例变量
obj1.name = "jack"
obj2.age = 18
obj1.sex = "male"       # 这一句会弹出错误
# 但是无法限制给类添加方法
Foo.show = print_doc
obj1.show()
obj2.show()
由于'sex'不在__slots__的列表中,所以不能绑定sex属性,试图绑定sex将得到AttributeError的错误。
Traceback (most recent call last):
  File "F:/Python/pycharm/201705/1.py", line 14, in <module>
    obj1.sex = "male"
AttributeError: 'Foo' object has no attribute 'sex'

Member protection and access control

private member

Those with double underscores are private variables, which can only be accessed within the class and cannot be accessed from outside.

class obj:
    def __init__(self,name):
        self.name=name
    def pri(self):
        print self.name
    __age = 18
    # 加上双下划线的就是私有变量,只能在类的内部访问,外部无法访问
a = obj('zhao')
a.pri()

If you want to call this private member in the class, you can use it like this

class obj:
    def __init__(self,name):
        self.name=name
    def prin(self):
        print self.name
    __age = 18
    # 加上双下划线的就是私有变量,只能在类的内部访问,外部无法访问
    @classmethod
    # 如果要在类中调用,首先调用类方法
    def pri(cls):
        print cls.__age
        # 然后在使用
a = obj('zhao')
a.prin()
obj.pri()
# 通过这样直接调用类中的私有变量

Use the get-set-del method to operate private members

class obj:
    def __init__(self,name):
        self.name=name
    def prin(self):
        print self.name
    __age = 18
    # 加上双下划线的就是私有变量,只能在类的内部访问,外部无法访问
    @classmethod
    # 如果要在类中调用,首先调用类方法
    def pri(cls):
        print cls.__age
        # 然后在使用
    @classmethod
    def set_age(cls,value):
        cls.__age = value
        return cls.__age
        # 这个用法就是改变__age的值
    @classmethod
    def get_age(cls):
        return cls.__age
        # 这个用法就是直接返回__age的值
    @classmethod
    def del_age(cls):
        del cls.__age
        # 这个用法就是直接删除__age的值

print obj.get_age()
# 这里是直接调用出__age的值  返回值18
print obj.set_age(20)
# 这里是直接改变__age的值  返回值20
obj.del_age()
# 这里是直接删除__age的值

Supongo que te gusta

Origin blog.csdn.net/qq_36820823/article/details/123727010
Recomendado
Clasificación