GVKun编程网logo

使用ObjectIdentifier()和'==='运算符之间的区别(object.is()用法)

12

在本文中,我们将详细介绍使用ObjectIdentifier的各个方面,并为您提供关于和'==='运算符之间的区别的相关解答,同时,我们也将为您带来关于adifferentobjectwiththes

在本文中,我们将详细介绍使用ObjectIdentifier的各个方面,并为您提供关于和'==='运算符之间的区别的相关解答,同时,我们也将为您带来关于a different object with the same identifier val...、actionscript-3 – Object和*之间的区别?、angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])、Beautifulsoup:.find()和.select()之间的区别的有用知识。

本文目录一览:

使用ObjectIdentifier()和'==='运算符之间的区别(object.is()用法)

使用ObjectIdentifier()和'==='运算符之间的区别(object.is()用法)

假设我正在Swift中实现一个根类,我声明该根类采用了Equatable协议(我希望能够知道我类型的数组是否包含给定的实例)。

*在此特定情况下,将协议的所需==运算符实现为之间有 *什么区别( 如果有的话):

public static func ==(lhs: MyClass, rhs: MyClass) -> Bool {    return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)}

…而不是仅仅这样做:

public static func ==(lhs: MyClass, rhs: MyClass) -> Bool {    return (lhs === rhs)}

作为参考,这是文档中所说的ObjectIdentifier()

类实例或元类型的唯一标识符。在Swift中,只有类实例和元类型才具有唯一标识。对于结构,枚举,函数或元组,没有身份的概念。

......这是什么的“基本算法”一节雨燕编程语言(斯威夫特3)表示,有关===操作:

注意

Swift还提供了两个标识运算符(===!==),用于测试两个对象引用是否都引用同一对象实例。有关更多信息,请参见类和结构。

答案1

小编典典

类实例没有区别,请参见ObjectIdentifier.swift中的以下
注释:

  /// Creates an instance that uniquely identifies the given class instance.  ///  /// The following example creates an example class `A` and compares instances  /// of the class using their object identifiers and the identical-to  /// operator (`===`):  ///  ///     class IntegerRef {  ///         let value: Int  ///         init(_ value: Int) {  ///             self.value = value  ///         }  ///     }  ///  ///     let x = IntegerRef(10)  ///     let y = x  ///  ///     print(ObjectIdentifier(x) == ObjectIdentifier(y))  ///     // Prints "true"  ///     print(x === y)  ///     // Prints "true"  ///  ///     let z = IntegerRef(10)  ///     print(ObjectIdentifier(x) == ObjectIdentifier(z))  ///     // Prints "false"  ///     print(x === z)  ///     // Prints "false"  ///

从for的实现中==``ObjectIdentifier也可以明显看出,该
实现只比较指向对象存储的指针:

  public static func == (x: ObjectIdentifier, y: ObjectIdentifier) -> Bool {    return Bool(Builtin.cmp_eq_RawPointer(x._value, y._value))  }

这正是该===操作
确实还有:

public func === (lhs: AnyObject?, rhs: AnyObject?) -> Bool {  switch (lhs, rhs) {  case let (l?, r?):    return Bool(Builtin.cmp_eq_RawPointer(        Builtin.bridgeToRawPointer(Builtin.castToUnknownObject(l)),        Builtin.bridgeToRawPointer(Builtin.castToUnknownObject(r))      ))  case (nil, nil):    return true  default:    return false  }}

ObjectIdentifier符合Hashable,因此如果要为您的类实现该协议,将非常有用:

extension MyClass: Hashable {    var hashValue: Int {        return ObjectIdentifier(self).hashValue    }}

还可以为未定义的元类型(例如ObjectIdentifier(Float.self))创建对象标识符===

a different object with the same identifier val...

a different object with the same identifier val...

a different object with the same identifier value was already associated with the session
一个经典的 hibernate 错误:a different object with the same identifier value was already associated with the session xxxx
hibernate3.0 以上使用 merge () 来合并两个 session 中的同一对象
具体到我自己的代码就是
public Object getDomain(Object obj) {
  getHibernateTemplate().refresh(obj);
  return obj;
  }
  public void deleteDomain(Object obj) {
  obj = getHibernateTemplate().merge(obj);
  getHibernateTemplate().delete(obj);
  }


解决 a different object with the same identifier value was already associated with the session 错误 

这个错误我一共遇到过两次,一直没有找到很好的解决方案,这个错误产生原因相信大家都知道,因为在 hibernate 中同一个 session 里面有了两个相同标识但是是不同实体,当这时运行 saveOrUpdate (object) 操作的时候就会报这个错误。呵呵,也许你会说,你这么说跟没说没什么区别,我承认,呵呵,我不知道具体为什么会产生这个错误,要不然也不会很久都没有解决,现在,给出一个临时的解决方案,给向我一样,没有办法找到根源的人一个能够继续执行下去的方法(当然是对的,只是不是从产生原因入手)

其实要解决这个问题很简单,只需要进行 session.clean () 操作就可以解决了,但是你在 clean 操作后面又进行了 saveOrUpdate (object) 操作,有可能会报出 "Found two representations of same collection",我找了很多资料,没有什么很好的解释,其中这篇文章帮助最大 [url] http://opensource.atlassian.com/projects/hibernate/browse/HHH-509 [/url]。

最后通过 session.refresh (object) 方法就可以解决了,注意,当 object 不是数据库中已有数据的对象的时候,不能使用 session.refresh (object) 因为 refresh 是从 hibernate 的 session 中去重新取 object,如果 session 中没有这个对象,则会报错所以当你使用 saveOrUpdate (object) 之前还需要判断一下

当然这个问题最容易解决的办法还是使用 Hibernate 里面自带的 merge () 方法。不过我始终觉得碰到问题就用这种软件自带的非常用方法(和 saveOrUpdate (),save (),update () 相比)感觉十分不爽。

后来我还发现这种错误经常出现在一对多映射和多对多映射,请大家在使用一对多和多对多映射的时候要小心一些


Hibernate 疑难异常及处理


1、a different object with the same identifier value was already associated with the session。

  错误原因:在 hibernate 中同一个 session 里面有了两个相同标识但是是不同实体。

  解决方法一:session.clean ()

  PS:如果在 clean 操作后面又进行了 saveOrUpdate (object) 等改变数据状态的操作,有可能会报出 "Found two representations of same collection" 异常。

  解决方法二:session.refresh (object)

  PS:当 object 不是数据库中已有数据的对象的时候,不能使用 session.refresh (object) 因为该方法是从 hibernate 的 session 中去重新取 object,如果 session 中没有这个对象,则会报错所以当你使用 saveOrUpdate (object) 之前还需要判断一下。

  解决方法三:session.merge (object)

  PS:Hibernate 里面自带的方法,推荐使用。

2、Found two representations of same collection

  错误原因:见 1。

  解决方法:session.merge (object)

以上两中异常经常出现在一对多映射和多对多映射中


a different object with the same identifier value was already associated with the session
一个经典的 hibernate 错误:a different object with the same identifier value was already associated with the session xxxx
hibernate3.0 以上使用 merge () 来合并两个 session 中的同一对象
具体到我自己的代码就是
public Object getDomain(Object obj) {
  getHibernateTemplate().refresh(obj);
  return obj;
  }
  public void deleteDomain(Object obj) {
  obj = getHibernateTemplate().merge(obj);
  getHibernateTemplate().delete(obj);
  }
==================== 我是分割线 ===================
其实我的解决办法是把 obj 给重新 merge 一下,注意红字部分
public Serializable save(Object persistentObject) throws DaoException {
  try {
        
  Session session = this.openSession();
  beginTransaction();
  persistentObject = session.merge(persistentObject);
  Serializable id = session.save(persistentObject);
  if (autoCommit)
  commitTransaction();
  return id;
  } catch (HibernateException ex) {
  log.error("Fail to save persistentObject", ex);
  throw new DaoException("Fail to save persistentObject", ex);
  } finally {
  if (autoCloseSession)
  closeSession();
  }
  }

actionscript-3 – Object和*之间的区别?

actionscript-3 – Object和*之间的区别?

声明变量时应该使用的内容如下:
private var someVar:*;

要么

private var someVar:Object;

两者有什么区别?
是什么让一个人在各种情况下优于其他人?任何例子?

谢谢.

解决方法

someVar:*是一个特殊的无类型var,它保持默认值undefined while

对象var默认值为null.

这是唯一的关键区别.

angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])

angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])

我遇到了下一个错误,无法理解如何解决它.

Can’t resolve all parameters for AuthenticationService: ([object Object],?,[object Object])

我已经检查了几乎每个主题,并尝试了多种方法来解决它,但仍然无法在第二天击败它.

我试图像这样在appService中注入第一个authService但是得到了同样的错误

@Inject(forwardRef(() => AuthenticationService)) public authService: AuthenticationService

我检查了所有DI和服务内部的导入顺序,在我看来一切都是正确的

如果有人可以帮我处理它,我很感激.

Angular 4.0.0

AuthService

import { Injectable } from '@angular/core';
import {Http,Headers,Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';

import {AppServices} from "../../app.services";
import {Router} from "@angular/router";

@Injectable()
export class AuthenticationService {
  public token: any;

  constructor(
    private http: Http,private appService: AppServices,private router: Router
  ) {
    this.token = localStorage.getItem('token');
  }

  login(username: string,password: string): Observable<boolean> {
    let headers = new Headers();
    let body = null;
    headers.append("Authorization",("Basic " + btoa(username + ':' + password)));

    return this.http.post(this.appService.api + '/login',body,{headers: headers})
      .map((response: Response) => {
        let token = response.json() && response.json().token;
        if (token) {
          this.token = token;
          localStorage.setItem('Conform_token',token);
          return true;
        } else {
          return false;
        }
      });
  }

  logout(): void {
    this.token = null;
    localStorage.removeItem('Conform_token');
    this.router.navigate(['/login']);
  }
}

应用服务

import {Injectable} from '@angular/core';
import {Headers,Http,RequestOptions} from '@angular/http';
import {Router} from "@angular/router";
import {AuthenticationService} from "./auth/auth.service";

import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';

@Injectable()

export class AppServices {

  api = '//endpoint/';

  public options: any;
  constructor(
    private http: Http,private router: Router,public authService: AuthenticationService // doesn't work
  //  @Inject(forwardRef(() => AuthenticationService)) public authService: AuthenticationService // doesn't work either
      ) {
        let head = new Headers({
      'Authorization': 'Bearer ' + this.authService.token,"Content-Type": "application/json; charset=utf8"
    });
    this.options = new RequestOptions({headers: head});
  }

  // ====================
  //    data services
  // ====================

  getData(): Promise<any> {
    return this.http
      .get(this.api + "/data",this.options)
      .toPromise()
      .then(response => response.json() as Array<Object>)
      .catch((err)=>{this.handleError(err);})
  }

应用模块

import { browserModule } from '@angular/platform-browser';
import { browserAnimationsModule } from '@angular/platform-browser/animations';

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {BaseRequestOptions,HttpModule} from '@angular/http';

import { MaterialModule} from '@angular/material';
import {FlexLayoutModule} from "@angular/flex-layout";
import 'hammerjs';

import { routing,appRoutingProviders }  from './app.routing';
import { AppServices } from './app.services';
import {AuthGuard} from "./auth/auth.guard";
import {AuthenticationService} from "./auth/auth.service";

import {AppComponent} from './app.component';
import {AuthComponent} from './auth/auth.component';
import {NotFoundComponent} from './404/not-found.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,AuthComponent,NotFoundComponent,HomeComponent
  ],imports: [
    browserModule,browserAnimationsModule,FormsModule,HttpModule,routing,MaterialModule,FlexLayoutModule
  ],providers: [AppServices,AuthGuard,AuthenticationService],bootstrap: [AppComponent]
})
export class AppModule { }

解决方法

AppServices和AuthenticationService之间存在循环依赖关系 – 这与Angular使用的构造函数注入无法实现.

你可以使用

export class AuthenticationService {
  public token: any;
  appService: AppServices;
  constructor(
    private http: Http,// private appService: AppServices,injector:Injector;
    private router: Router
  ) {
    setTimeout(() => this.appService = injector.get(AppServices));
    this.token = localStorage.getItem('token');
  }

另见DI with cyclic dependency with custom HTTP and ConfigService

要避免使用setTimeout,您还可以从AppService的构造函数中设置AuthenticationService.appService(或者相反)

Beautifulsoup:.find()和.select()之间的区别

Beautifulsoup:.find()和.select()之间的区别

当您使用
BeautifulSoup

抓取网站的特定部分时,您可以使用

  • soup.find()soup.findAll()
  • soup.select()

.find().select()方法之间有区别吗?(例如,性能或灵活性等)还是相同?

答案1

小编典典

总结评论:

  • select 查找多个实例并返回一个列表, find 查找第一个实例,因此它们不会执行相同的操作。 select_one 将等同于 find
  • 我链接时,标签或使用几乎总是使用CSS选择 tag.classname ,如果寻找一个单一的元素没有一个类我用 找到 。本质上,它取决于用例和个人喜好。
  • 就灵活性而言,我认为您知道答案,soup.select("div[id=foo] > div > div > div[class=fee] > span > span > a")使用多个链接的 find / find_all 调用看起来很难看。
  • bs4中的css选择器唯一的问题是对它的支持非常有限, nth-of-type 是唯一实现的伪类,并且像c [sref ]的许多其他部分一样,也不支持链接属性,例如a [href] [src]。但是像 a [href = ..] *, a [href ^ =]a [href $ =] 等之类的东西我认为要好得多,find("a", href=re.compile(....))但这又是个人喜好。

为了提高性能,我们可以运行一些测试,我修改了此处答案的代码,该答案在从此处获取的800多个html文件上运行,虽然并不详尽,但应为某些选项的可读性和性能提供线索:

修改后的功能为:

from bs4 import BeautifulSoupfrom glob import iglobdef parse_find(soup):    author = soup.find("h4", class_="h12 talk-link__speaker").text    title = soup.find("h4", class_="h9 m5").text    date = soup.find("span", class_="meta__val").text.strip()    soup.find("footer",class_="footer").find_previous("data", {        "class": "talk-transcript__para__time"}).text.split(":")    soup.find_all("span",class_="talk-transcript__fragment")def parse_select(soup):    author = soup.select_one("h4.h12.talk-link__speaker").text    title = soup.select_one("h4.h9.m5").text    date = soup.select_one("span.meta__val").text.strip()    soup.select_one("footer.footer").find_previous("data", {        "class": "talk-transcript__para__time"}).text    soup.select("span.talk-transcript__fragment")def  test(patt, func):    for html in iglob(patt):        with open(html) as f:            func(BeautifulSoup(f, "lxml")

现在是时候了:

In [7]: from testing import test, parse_find, parse_selectIn [8]: timeit test("./talks/*.html",parse_find)1 loops, best of 3: 51.9 s per loopIn [9]: timeit test("./talks/*.html",parse_select)1 loops, best of 3: 32.7 s per loop

就像我说的并不详尽,但我认为我们可以肯定地说CSS选择器绝对有效。

今天关于使用ObjectIdentifier和'==='运算符之间的区别的分享就到这里,希望大家有所收获,若想了解更多关于a different object with the same identifier val...、actionscript-3 – Object和*之间的区别?、angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])、Beautifulsoup:.find()和.select()之间的区别等相关知识,可以在本站进行查询。

本文标签: