Hướng dẫn python create object if not exist - python tạo đối tượng nếu không tồn tại

Vòng lặp của bạn đang kiểm tra từng mục và nếu mục cụ thể đó không bằng nhau, nó sẽ tạo ra một trường hợp khác. Nhưng nếu mục cụ thể đó bằng nhau, nó không dừng lại, nó chỉ tiếp tục đến mục tiếp theo, điều này sẽ không bằng nhau. Đó là lý do tại sao bạn thực sự có hai mục bổ sung ở cuối.

Bạn có thể sửa chữa cái này bằng cách giữ một lá cờ:

found = False
for person in Person.personslist:
    if prompt_fname == person.fname and prompt_lname == person.lname:
        found = True
        break
if not found:
    Person[prompt_fname, prompt_lname]

Tuy nhiên, có một cách tốt hơn nhiều để làm điều này: cách của bạn rất không hiệu quả, vì nó đòi hỏi phải quét tuyến tính mỗi lần. Thay vào đó, hãy giữ một từ điển các đối tượng được khóa bởi tên đầy đủ của chúng:

class Person[object]:

    persons_dict = {}
    '''Creates a person object'''
    def __init__[self, firstname, lastname]:
        self.lname = lastname.title[]
        self.fname = firstname.title[]
        fullname = "%s %s" % [self.fname, self.lname]
        Person.persons_dict[fullname] = self

Và bây giờ bạn có thể chỉ cần kiểm tra trong một lần:

if "%s %s" % [prompt_fname, prompt_lname] not in Person.persons_dict:

44 Ví dụ về mã Python được tìm thấy liên quan đến "Tạo nếu không tồn tại". Bạn có thể bỏ phiếu cho những người bạn thích hoặc bỏ phiếu cho những người bạn không thích và đi đến dự án gốc hoặc tệp nguồn bằng cách theo các liên kết trên mỗi ví dụ. create if not exists". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

ví dụ 1

def create_secret_if_not_exists[self, cluster]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        secret = self.make_secret[name]
        secret["metadata"]["ownerReferences"] = [
            {
                "apiVersion": cluster["apiVersion"],
                "kind": cluster["kind"],
                "name": cluster["metadata"]["name"],
                "uid": cluster["metadata"]["uid"],
            }
        ]

        self.log.info["Creating new credentials for cluster %s.%s", namespace, name]
        try:
            await self.core_client.create_namespaced_secret[namespace, secret]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return secret["metadata"]["name"] 

Ví dụ 2

def create_dir_if_not_exists[self, dir_path]:
        """
        This method recursively creates a directory if not exists

        If the path exists and is not a directory raise an exception.

        :param str dir_path: full path for the directory
        """
        _logger.debug['Create directory %s if it does not exists' % dir_path]
        exists = self.exists[dir_path]
        if exists:
            is_dir = self.cmd['test', args=['-d', dir_path]]
            if is_dir != 0:
                raise FsOperationFailed[
                    'A file with the same name already exists']
            else:
                return False
        else:
            # Make parent directories if needed
            mkdir_ret = self.cmd['mkdir', args=['-p', dir_path]]
            if mkdir_ret == 0:
                return True
            else:
                raise FsOperationFailed['mkdir execution failed'] 

Ví dụ 3

def create_ingressroute_if_not_exists[self, cluster, sched_pod]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        route = self.make_ingressroute[name, namespace]
        route["metadata"]["ownerReferences"] = [
            {
                "apiVersion": "v1",
                "kind": "Pod",
                "name": sched_pod["metadata"]["name"],
                "uid": sched_pod["metadata"]["uid"],
            }
        ]

        self.log.info[
            "Creating scheduler HTTP route for cluster %s.%s", namespace, name
        ]
        try:
            await self.custom_client.create_namespaced_custom_object[
                "traefik.containo.us", "v1alpha1", namespace, "ingressroutes", route
            ]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return route["metadata"]["name"] 

Ví dụ 4

def createHashDatabaseIfNotExists[self]:
        log.debug['Creating hash db in database']
        try:
            connection = mysql.connector.connect[host=self.host,
                                                 user=self.user, port=self.port, passwd=self.password,
                                                 db=self.database]
        except:
            log.error["Could not connect to the SQL database"]
            return False
        cursor = connection.cursor[]
        query = [' Create table if not exists trshash [ ' +
                 ' hashid MEDIUMINT NOT NULL AUTO_INCREMENT, ' +
                 ' hash VARCHAR[255] NOT NULL, ' +
                 ' type VARCHAR[10] NOT NULL, ' +
                 ' id VARCHAR[255] NOT NULL, ' +
                 ' count INT[10] NOT NULL DEFAULT 1, ' +
                 ' modify DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, ' +
                 ' PRIMARY KEY [hashid]]']
        log.debug[query]
        cursor.execute[query]
        connection.commit[]
        cursor.close[]
        connection.close[]
        return True 

Ví dụ 5

def create_cert_if_not_exists[self, cap_name, pem_file]:
    if not os.path.isfile[pem_file]:
      logger.debug['Generating certificate and key: %s', pem_file]

      cert_dict = self.config['capabilities'][cap_name][
          'protocol_specific_data']['cert']
      cert_cn = cert_dict['common_name']
      cert_country = cert_dict['country']
      cert_state = cert_dict['state']
      cert_locality = cert_dict['locality']
      cert_org = cert_dict['organization']
      cert_org_unit = cert_dict['organizational_unit']
      valid_days = int[cert_dict['valid_days']]
      serial_number = int[cert_dict['serial_number']]

      cert, key = common.generate_self_signed_cert[cert_country, cert_state,
                                                   cert_org, cert_locality,
                                                   cert_org_unit, cert_cn,
                                                   valid_days, serial_number]
      with open[pem_file, 'wb'] as _pem_file:
        _pem_file.write[cert]
        _pem_file.write[key] 

Ví dụ 6

def create_lease_store_if_not_exists_async[self]:
        """
        Create the lease store if it does not exist, do nothing if it does exist.

        :return: `True` if the lease store already exists or was created successfully, `False` if not.
        :rtype: bool
        """
        try:
            await self.host.loop.run_in_executor[
                self.executor,
                functools.partial[
                    self.storage_client.create_container,
                    self.lease_container_name]]

        except Exception as err:  # pylint: disable=broad-except
            _logger.error["%r", err]
            raise err

        return True 

Ví dụ 7

def create_service_if_not_exists[self, cluster, sched_pod]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        service = self.make_service[name]
        service["metadata"]["ownerReferences"] = [
            {
                "apiVersion": "v1",
                "kind": "Pod",
                "name": sched_pod["metadata"]["name"],
                "uid": sched_pod["metadata"]["uid"],
            }
        ]

        self.log.info["Creating scheduler service for cluster %s.%s", namespace, name]
        try:
            await self.core_client.create_namespaced_service[namespace, service]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return service["metadata"]["name"] 

Ví dụ 8

class Person[object]:

    persons_dict = {}
    '''Creates a person object'''
    def __init__[self, firstname, lastname]:
        self.lname = lastname.title[]
        self.fname = firstname.title[]
        fullname = "%s %s" % [self.fname, self.lname]
        Person.persons_dict[fullname] = self
0

Ví dụ 9

class Person[object]:

    persons_dict = {}
    '''Creates a person object'''
    def __init__[self, firstname, lastname]:
        self.lname = lastname.title[]
        self.fname = firstname.title[]
        fullname = "%s %s" % [self.fname, self.lname]
        Person.persons_dict[fullname] = self
1

Ví dụ 10

class Person[object]:

    persons_dict = {}
    '''Creates a person object'''
    def __init__[self, firstname, lastname]:
        self.lname = lastname.title[]
        self.fname = firstname.title[]
        fullname = "%s %s" % [self.fname, self.lname]
        Person.persons_dict[fullname] = self
2

Ví dụ 11

class Person[object]:

    persons_dict = {}
    '''Creates a person object'''
    def __init__[self, firstname, lastname]:
        self.lname = lastname.title[]
        self.fname = firstname.title[]
        fullname = "%s %s" % [self.fname, self.lname]
        Person.persons_dict[fullname] = self
3

Ví dụ 12

class Person[object]:

    persons_dict = {}
    '''Creates a person object'''
    def __init__[self, firstname, lastname]:
        self.lname = lastname.title[]
        self.fname = firstname.title[]
        fullname = "%s %s" % [self.fname, self.lname]
        Person.persons_dict[fullname] = self
4

Ví dụ 13

class Person[object]:

    persons_dict = {}
    '''Creates a person object'''
    def __init__[self, firstname, lastname]:
        self.lname = lastname.title[]
        self.fname = firstname.title[]
        fullname = "%s %s" % [self.fname, self.lname]
        Person.persons_dict[fullname] = self
5

Ví dụ 14

class Person[object]:

    persons_dict = {}
    '''Creates a person object'''
    def __init__[self, firstname, lastname]:
        self.lname = lastname.title[]
        self.fname = firstname.title[]
        fullname = "%s %s" % [self.fname, self.lname]
        Person.persons_dict[fullname] = self
6

Ví dụ 15

class Person[object]:

    persons_dict = {}
    '''Creates a person object'''
    def __init__[self, firstname, lastname]:
        self.lname = lastname.title[]
        self.fname = firstname.title[]
        fullname = "%s %s" % [self.fname, self.lname]
        Person.persons_dict[fullname] = self
7

Ví dụ 16

class Person[object]:

    persons_dict = {}
    '''Creates a person object'''
    def __init__[self, firstname, lastname]:
        self.lname = lastname.title[]
        self.fname = firstname.title[]
        fullname = "%s %s" % [self.fname, self.lname]
        Person.persons_dict[fullname] = self
8

Ví dụ 17

class Person[object]:

    persons_dict = {}
    '''Creates a person object'''
    def __init__[self, firstname, lastname]:
        self.lname = lastname.title[]
        self.fname = firstname.title[]
        fullname = "%s %s" % [self.fname, self.lname]
        Person.persons_dict[fullname] = self
9

Ví dụ 18

if "%s %s" % [prompt_fname, prompt_lname] not in Person.persons_dict:
0

Ví dụ 19

if "%s %s" % [prompt_fname, prompt_lname] not in Person.persons_dict:
1

Ví dụ 20

if "%s %s" % [prompt_fname, prompt_lname] not in Person.persons_dict:
2

Ví dụ 21

if "%s %s" % [prompt_fname, prompt_lname] not in Person.persons_dict:
3

Ví dụ 22

if "%s %s" % [prompt_fname, prompt_lname] not in Person.persons_dict:
4

Ví dụ 23

if "%s %s" % [prompt_fname, prompt_lname] not in Person.persons_dict:
5

Ví dụ 24

if "%s %s" % [prompt_fname, prompt_lname] not in Person.persons_dict:
6

Ví dụ 25

if "%s %s" % [prompt_fname, prompt_lname] not in Person.persons_dict:
7

Ví dụ 26

if "%s %s" % [prompt_fname, prompt_lname] not in Person.persons_dict:
8

Ví dụ 27

if "%s %s" % [prompt_fname, prompt_lname] not in Person.persons_dict:
9

Ví dụ 28

def create_secret_if_not_exists[self, cluster]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        secret = self.make_secret[name]
        secret["metadata"]["ownerReferences"] = [
            {
                "apiVersion": cluster["apiVersion"],
                "kind": cluster["kind"],
                "name": cluster["metadata"]["name"],
                "uid": cluster["metadata"]["uid"],
            }
        ]

        self.log.info["Creating new credentials for cluster %s.%s", namespace, name]
        try:
            await self.core_client.create_namespaced_secret[namespace, secret]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return secret["metadata"]["name"] 
0

Ví dụ 29

def create_secret_if_not_exists[self, cluster]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        secret = self.make_secret[name]
        secret["metadata"]["ownerReferences"] = [
            {
                "apiVersion": cluster["apiVersion"],
                "kind": cluster["kind"],
                "name": cluster["metadata"]["name"],
                "uid": cluster["metadata"]["uid"],
            }
        ]

        self.log.info["Creating new credentials for cluster %s.%s", namespace, name]
        try:
            await self.core_client.create_namespaced_secret[namespace, secret]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return secret["metadata"]["name"] 
1

Ví dụ 30

def create_secret_if_not_exists[self, cluster]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        secret = self.make_secret[name]
        secret["metadata"]["ownerReferences"] = [
            {
                "apiVersion": cluster["apiVersion"],
                "kind": cluster["kind"],
                "name": cluster["metadata"]["name"],
                "uid": cluster["metadata"]["uid"],
            }
        ]

        self.log.info["Creating new credentials for cluster %s.%s", namespace, name]
        try:
            await self.core_client.create_namespaced_secret[namespace, secret]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return secret["metadata"]["name"] 
2

Ví dụ 31

def create_secret_if_not_exists[self, cluster]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        secret = self.make_secret[name]
        secret["metadata"]["ownerReferences"] = [
            {
                "apiVersion": cluster["apiVersion"],
                "kind": cluster["kind"],
                "name": cluster["metadata"]["name"],
                "uid": cluster["metadata"]["uid"],
            }
        ]

        self.log.info["Creating new credentials for cluster %s.%s", namespace, name]
        try:
            await self.core_client.create_namespaced_secret[namespace, secret]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return secret["metadata"]["name"] 
3

Ví dụ 32

def create_secret_if_not_exists[self, cluster]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        secret = self.make_secret[name]
        secret["metadata"]["ownerReferences"] = [
            {
                "apiVersion": cluster["apiVersion"],
                "kind": cluster["kind"],
                "name": cluster["metadata"]["name"],
                "uid": cluster["metadata"]["uid"],
            }
        ]

        self.log.info["Creating new credentials for cluster %s.%s", namespace, name]
        try:
            await self.core_client.create_namespaced_secret[namespace, secret]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return secret["metadata"]["name"] 
4

Ví dụ 33

def create_secret_if_not_exists[self, cluster]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        secret = self.make_secret[name]
        secret["metadata"]["ownerReferences"] = [
            {
                "apiVersion": cluster["apiVersion"],
                "kind": cluster["kind"],
                "name": cluster["metadata"]["name"],
                "uid": cluster["metadata"]["uid"],
            }
        ]

        self.log.info["Creating new credentials for cluster %s.%s", namespace, name]
        try:
            await self.core_client.create_namespaced_secret[namespace, secret]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return secret["metadata"]["name"] 
5

Ví dụ 34

def create_secret_if_not_exists[self, cluster]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        secret = self.make_secret[name]
        secret["metadata"]["ownerReferences"] = [
            {
                "apiVersion": cluster["apiVersion"],
                "kind": cluster["kind"],
                "name": cluster["metadata"]["name"],
                "uid": cluster["metadata"]["uid"],
            }
        ]

        self.log.info["Creating new credentials for cluster %s.%s", namespace, name]
        try:
            await self.core_client.create_namespaced_secret[namespace, secret]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return secret["metadata"]["name"] 
6

Ví dụ 35

def create_secret_if_not_exists[self, cluster]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        secret = self.make_secret[name]
        secret["metadata"]["ownerReferences"] = [
            {
                "apiVersion": cluster["apiVersion"],
                "kind": cluster["kind"],
                "name": cluster["metadata"]["name"],
                "uid": cluster["metadata"]["uid"],
            }
        ]

        self.log.info["Creating new credentials for cluster %s.%s", namespace, name]
        try:
            await self.core_client.create_namespaced_secret[namespace, secret]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return secret["metadata"]["name"] 
7

Ví dụ 36

def create_secret_if_not_exists[self, cluster]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        secret = self.make_secret[name]
        secret["metadata"]["ownerReferences"] = [
            {
                "apiVersion": cluster["apiVersion"],
                "kind": cluster["kind"],
                "name": cluster["metadata"]["name"],
                "uid": cluster["metadata"]["uid"],
            }
        ]

        self.log.info["Creating new credentials for cluster %s.%s", namespace, name]
        try:
            await self.core_client.create_namespaced_secret[namespace, secret]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return secret["metadata"]["name"] 
8

Ví dụ 37

def create_secret_if_not_exists[self, cluster]:
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        secret = self.make_secret[name]
        secret["metadata"]["ownerReferences"] = [
            {
                "apiVersion": cluster["apiVersion"],
                "kind": cluster["kind"],
                "name": cluster["metadata"]["name"],
                "uid": cluster["metadata"]["uid"],
            }
        ]

        self.log.info["Creating new credentials for cluster %s.%s", namespace, name]
        try:
            await self.core_client.create_namespaced_secret[namespace, secret]
        except ApiException as exc:
            if exc.status != 409:
                raise

        return secret["metadata"]["name"] 
9

Ví dụ 38

def create_dir_if_not_exists[self, dir_path]:
        """
        This method recursively creates a directory if not exists

        If the path exists and is not a directory raise an exception.

        :param str dir_path: full path for the directory
        """
        _logger.debug['Create directory %s if it does not exists' % dir_path]
        exists = self.exists[dir_path]
        if exists:
            is_dir = self.cmd['test', args=['-d', dir_path]]
            if is_dir != 0:
                raise FsOperationFailed[
                    'A file with the same name already exists']
            else:
                return False
        else:
            # Make parent directories if needed
            mkdir_ret = self.cmd['mkdir', args=['-p', dir_path]]
            if mkdir_ret == 0:
                return True
            else:
                raise FsOperationFailed['mkdir execution failed'] 
0

Ví dụ 39

def create_dir_if_not_exists[self, dir_path]:
        """
        This method recursively creates a directory if not exists

        If the path exists and is not a directory raise an exception.

        :param str dir_path: full path for the directory
        """
        _logger.debug['Create directory %s if it does not exists' % dir_path]
        exists = self.exists[dir_path]
        if exists:
            is_dir = self.cmd['test', args=['-d', dir_path]]
            if is_dir != 0:
                raise FsOperationFailed[
                    'A file with the same name already exists']
            else:
                return False
        else:
            # Make parent directories if needed
            mkdir_ret = self.cmd['mkdir', args=['-p', dir_path]]
            if mkdir_ret == 0:
                return True
            else:
                raise FsOperationFailed['mkdir execution failed'] 
1

Ví dụ 40

def create_dir_if_not_exists[self, dir_path]:
        """
        This method recursively creates a directory if not exists

        If the path exists and is not a directory raise an exception.

        :param str dir_path: full path for the directory
        """
        _logger.debug['Create directory %s if it does not exists' % dir_path]
        exists = self.exists[dir_path]
        if exists:
            is_dir = self.cmd['test', args=['-d', dir_path]]
            if is_dir != 0:
                raise FsOperationFailed[
                    'A file with the same name already exists']
            else:
                return False
        else:
            # Make parent directories if needed
            mkdir_ret = self.cmd['mkdir', args=['-p', dir_path]]
            if mkdir_ret == 0:
                return True
            else:
                raise FsOperationFailed['mkdir execution failed'] 
2

Ví dụ 41

def create_dir_if_not_exists[self, dir_path]:
        """
        This method recursively creates a directory if not exists

        If the path exists and is not a directory raise an exception.

        :param str dir_path: full path for the directory
        """
        _logger.debug['Create directory %s if it does not exists' % dir_path]
        exists = self.exists[dir_path]
        if exists:
            is_dir = self.cmd['test', args=['-d', dir_path]]
            if is_dir != 0:
                raise FsOperationFailed[
                    'A file with the same name already exists']
            else:
                return False
        else:
            # Make parent directories if needed
            mkdir_ret = self.cmd['mkdir', args=['-p', dir_path]]
            if mkdir_ret == 0:
                return True
            else:
                raise FsOperationFailed['mkdir execution failed'] 
3

Ví dụ 42

def create_dir_if_not_exists[self, dir_path]:
        """
        This method recursively creates a directory if not exists

        If the path exists and is not a directory raise an exception.

        :param str dir_path: full path for the directory
        """
        _logger.debug['Create directory %s if it does not exists' % dir_path]
        exists = self.exists[dir_path]
        if exists:
            is_dir = self.cmd['test', args=['-d', dir_path]]
            if is_dir != 0:
                raise FsOperationFailed[
                    'A file with the same name already exists']
            else:
                return False
        else:
            # Make parent directories if needed
            mkdir_ret = self.cmd['mkdir', args=['-p', dir_path]]
            if mkdir_ret == 0:
                return True
            else:
                raise FsOperationFailed['mkdir execution failed'] 
4

Ví dụ 43

def create_dir_if_not_exists[self, dir_path]:
        """
        This method recursively creates a directory if not exists

        If the path exists and is not a directory raise an exception.

        :param str dir_path: full path for the directory
        """
        _logger.debug['Create directory %s if it does not exists' % dir_path]
        exists = self.exists[dir_path]
        if exists:
            is_dir = self.cmd['test', args=['-d', dir_path]]
            if is_dir != 0:
                raise FsOperationFailed[
                    'A file with the same name already exists']
            else:
                return False
        else:
            # Make parent directories if needed
            mkdir_ret = self.cmd['mkdir', args=['-p', dir_path]]
            if mkdir_ret == 0:
                return True
            else:
                raise FsOperationFailed['mkdir execution failed'] 
5

Ví dụ 44

def create_dir_if_not_exists[self, dir_path]:
        """
        This method recursively creates a directory if not exists

        If the path exists and is not a directory raise an exception.

        :param str dir_path: full path for the directory
        """
        _logger.debug['Create directory %s if it does not exists' % dir_path]
        exists = self.exists[dir_path]
        if exists:
            is_dir = self.cmd['test', args=['-d', dir_path]]
            if is_dir != 0:
                raise FsOperationFailed[
                    'A file with the same name already exists']
            else:
                return False
        else:
            # Make parent directories if needed
            mkdir_ret = self.cmd['mkdir', args=['-p', dir_path]]
            if mkdir_ret == 0:
                return True
            else:
                raise FsOperationFailed['mkdir execution failed'] 
6

Chủ Đề