GVKun编程网logo

issubclasss/type/isinstance/callable/super

12

对于想了解issubclasss/type/isinstance/callable/super的读者,本文将提供新的信息,并且为您提供关于Build-inFunction:abs(),all(),an

对于想了解issubclasss/type/isinstance/callable/super的读者,本文将提供新的信息,并且为您提供关于Build-in Function:abs(),all(),any(),assii(),bin(),issubclass(),bytearray(),isinstance()、C# IsAssignableFrom与IsSubClassOf 判断匿名类是否继承父类、c# – Type.IsSubclassOf()在AppDomains中不起作用?、c# – 什么时候是obj.GetType().IsInstanceOfType(typeof(MyClass))是真的吗?的有价值信息。

本文目录一览:

issubclasss/type/isinstance/callable/super

issubclasss/type/isinstance/callable/super

issubclass() :

  方法用于判断第一个参数是否是第二个参数的子子孙孙类。

语法:issubclass(sub, super)

检查sub类是否是 super 类的派生类

class A:
     pass

class B(A):
    pass

 print issubclass(B,A)
type() 
  
给你一个参数,判断对象是不是由某一个指定类? --> type(obj) == Foo
class Foo(object):
    pass

class Bar(object):
    pass

def func(*args):
    foo_counter =0
    bar_counter =0
    for item in args:
        if type(item) == Foo:
            foo_counter += 1
        elif type(item) == Bar:
            bar_counter += 1
    return foo_counter,bar_counter

# result = func(Foo(),Bar(),Foo())
# print(result)

v1,v2 = func(Foo(),Bar(),Foo())
print(v1,v2)
实例

isinstance()

  来判断一个对象是否是一个已知的类型,类似 type()。

class Base(object):
    pass

class Foo(Base):
    pass

obj1 = Foo()
print(isinstance(obj1,Foo))  
print(isinstance(obj1,Base))
实例

callable()

   1,用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。

  2,对于函数, 方法, lambda 函式, 类, 以及实现了 __call__ 方法的类实例, 它都返回 True。

  3.,类对象都是可被调用对象,类的实例对象是否可调用对象,取决于类是否定义了__call__方法。

>>> class A: #定义类A
pass

>>> callable(A) #类A是可调用对象
True
>>> a = A() #调用类A
>>> callable(a) #实例a不可调用
False
>>> a() #调用实例a失败
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
a()
TypeError: ''A'' object is not callable


>>> class B: #定义类B
def __call__(self):
print(''instances are callable now.'')


>>> callable(B) #类B是可调用对象
True
>>> b = B() #调用类B
>>> callable(b) #实例b是可调用对象
True
>>> b() #调用实例b成功
instances are callable now.

super--主动调用其他类的方法:

class Base:

    def f1(self):
        print(''5个功能'')

class Foo:

    def f1(self):
        print(''3个功能'')
        Base.f1(obj)

obj = Foo()
obj.f1()
方法1
class Foo:
    def f1(self):
        super().f1()
        print(''3个功能'')

class Bar(object):
    def f1(self):
        print(''6个功能'')

class Info(Foo,Bar):
    pass

obj = Info()
obj.f1()
结果:
6个功能
3个功能
#super()是从当前位置找他的下一个方法
方法2

 

 

Build-in Function:abs(),all(),any(),assii(),bin(),issubclass(),bytearray(),isinstance()

Build-in Function:abs(),all(),any(),assii(),bin(),issubclass(),bytearray(),isinstance()

print(''abs():输出绝对值,是absolute的缩写--------------'')
print(abs(-1))

print(''all()与any()---------------------------'')
#all都为真时才为真,但是空的为真,any()有一个为真时就是真的
jo1_list=[1,2,3,4,5,6,7]
jo2_list=['''',2,3,4,5,7]
jo4_list=[0,2,3,4,5,6,7]
jo5_list=[False,2,3,4,5,6,7]
jo6_list=[]
jo7_list=[0,'''',False]
print(''all()列表元素不为空和零'',all(jo1_list))
print(''all()列表元素包含一个空'',all(jo2_list))
print(''all()列表元素包含一个0'',all(jo4_list))
print(''all()列表元素包含一个False'',all(jo5_list))
print(''all()列表元素为空'',all(jo6_list))
print(''all()列表元素为空、零和假'',all(jo7_list))

print(''any()列表元素不为空和零'',any(jo1_list))
print(''any()列表元素包含一个空'',any(jo2_list))
print(''any()列表元素包含一个0'',any(jo4_list))
print(''any()列表元素包含一个False'',any(jo5_list))
print(''any()列表元素为空'',any(jo6_list))
print(''all()列表元素为空、零和假'',any(jo7_list))

print(''ascii()-----------------------'')
print(''参数为数字,返回字符串'',ascii(10))
print(''参数为字符串,返回字符串'',ascii(''jojojo''))
print(''参数为汉字,返回字符串'',ascii(''呵呵哒''))

print(''bin()是binary的缩写--------------------------'')
print(bin(1))
print(bin(10000**1000))

print(''bool()---------'')
print(bool())
print(bool(0))
print(bool(1))
print(bool(2))

print(''issubclass()---'')
class jo:
    pass
class joo(jo):
    pass
class jook:
    pass
print(issubclass(joo,jo))
print(issubclass(jook,jo))

 

 

>>>> bytearray(''heheda'')
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    bytearray(''heheda'')
TypeError: string argument without an encoding
>>> bytearray(heheda)
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    bytearray(heheda)
NameError: name ''heheda'' is not defined
>>> bytearray(''heheda'',''''utf-8)
SyntaxError: invalid syntax
>>> bytearray(''heheda'',''utf-8'')
bytearray(b''heheda'')
>>> bytearray(''heheda'',''gb2312'')
bytearray(b''heheda'')
>>> bytearray(''heheda'',''BIG5'')
bytearray(b''heheda'')
>>> bytearray(''呵呵哒'',''BIG5'')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    bytearray(''呵呵哒'',''BIG5'')
UnicodeEncodeError: ''big5'' codec can''t encode character ''\u54d2'' in position 2: illegal multibyte sequence
>>> bytearray(''呵呵哒'',''gb2312'')
bytearray(b''\xba\xc7\xba\xc7\xdf\xd5'')
>>> bytearray(''呵呵哒'',''utf-8'')
bytearray(b''\xe5\x91\xb5\xe5\x91\xb5\xe5\x93\x92'')
>>> is
SyntaxError: invalid syntax
>>> isinstance(jojo,str)
Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    isinstance(jojo,str)
NameError: name ''jojo'' is not defined
>>> isinstance(''jojo'',str)
True
>>> isinstance(''jojo'',unicode)
Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    isinstance(''jojo'',unicode)
NameError: name ''unicode'' is not defined
>>> isinstance(''jojo'',''utf-8'')
Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    isinstance(''jojo'',''utf-8'')
TypeError: isinstance() arg 2 must be a type or tuple of types
>>> isinstance(''jojo'',''utf-8'')

 

C# IsAssignableFrom与IsSubClassOf 判断匿名类是否继承父类

C# IsAssignableFrom与IsSubClassOf 判断匿名类是否继承父类

 

 

public class Dog : Animal
    {
        public string name { get; set; }
    }
    public class Animal
    {
        public string id { get; set; }
    }

    public class Main
    {
        public void Main()
        {
            Dog aa = new Dog { name = "", id = "动物" };
            CheckClass(aa);
        }
        public void CheckClass<T>(T entity)
        {
            bool re1 = typeof(Animal).IsAssignableFrom(typeof(T));
            //返回true的条件是Dog类直接或间接的实现了Animal类;
            bool re2 = typeof(T).IsSubclassOf(typeof(Animal));
            //返回true的条件是Dog类是Animal的子类
            
            var id = (entity as Animal).id;
        }
    }

 

c# – Type.IsSubclassOf()在AppDomains中不起作用?

c# – Type.IsSubclassOf()在AppDomains中不起作用?

我在使用以下代码时遇到了一些问题:
private class ClientPluginLoader : MarshalByRefObject
{
    public bool IsPluginAssembly(string filename)
    {
        AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomainReflectionOnlyAssemblyResolve);

        Assembly asm = Assembly.ReflectionOnlyLoadFrom(filename);

        Type[] types = asm.GetTypes();
        foreach (Type type in types)
        {
            if (type.IsSubclassOf(typeof(ClientPlugin)))
            {
                return true;
            }
        }

        return false;
    }
}

代码是通过我通过自定义应用程序域的CreateInstanceFromAndUnwrap()创建的代理调用的.这意味着IsPluginAssembly()在我的自定义应用程序域的上下文中执行.

问题是对IsSubclassOf()的调用总是返回false,即使它应该返回true.所讨论的“类型”确实从ClientPlugin继承 – 毫无疑问.

ClientPlugin是在一个不同的私有程序集中定义的,我正在手动解析,如上面的代码片段所示.

我在if(type.IsSubclassOf(…))行上设置了一个断点,并确认该表达式为false:

type.BaseType == typeof(ClientPlugin)

另一方面,这个表达式是正确的:

type.BaseType.FullName == typeof(ClientPlugin).FullName

这怎么可能?这是怎么回事?

更新:Kent Boogaart向我指出了正确的方向.我在网上搜索了一下,然后进入this博客文章.我似乎必须解决我的Load / LoadFrom / ReflectionOnlyLoadFrom冲突才能使其工作.

解决方法

这是由于加载到不同的上下文.加载程序集的方式(Load / LoadFrom / ReflectionOnlyLoad)确定加载程序集的上下文.这个简单的例子也证明了这个问题:
using System;
using System.Reflection;

class Foo
{
    public static void Main()
    {
        var type = typeof(Foo);
        var reflectionLoadType = Assembly.ReflectionOnlyLoad("ConsoleApplication1").GetType("Foo");
        Console.WriteLine(type == reflectionLoadType);  //false
        Console.WriteLine(type.Equals(reflectionLoadType));  //false

        Console.WriteLine("DONE");
        Console.ReadKey();
    }
}

有关详细信息,请参阅here.

c# – 什么时候是obj.GetType().IsInstanceOfType(typeof(MyClass))是真的吗?

c# – 什么时候是obj.GetType().IsInstanceOfType(typeof(MyClass))是真的吗?

我正在看别人写的这段代码,我想知道它什么时候会评估为真.基本上,它说someType是someOtherType的一个实例.它甚至有意义吗?到目前为止,我已经尝试过:

derivedClass.GetType().isinstanceOfType(typeof(BaseClass)) 

baseClass.GetType().isinstanceOfType(typeof(DerivedClass)) 

myClass.GetType().isinstanceOfType(typeof(MyClass))

并且所有人都评价为假.

任何帮助表示赞赏.

解决方法

只有当涉及的对象(derivedClass,baseClass和myClass)是对象的实例或未记录的RuntimeType对象(注意 Type是抽象的)时,这3行中的每一行都将返回true,因此例如以下将导致true声明:

var myObject = new object();
myObject.GetType().isinstanceOfType(typeof(Console));

myObject = typeof(Object);
myObject.GetType().isinstanceOfType(typeof(Console));

请注意,使用的类型(在本例中为Console)无关紧要,并且对语句的结果没有影响.

为什么?

IsInstanceOfType的文档告诉我们,如果传入的对象是当前类型的实例,它将返回true,例如,如果myForm是一个派生自Form的类,则以下语句将返回true,否则它将返回false.

typeof(Form).isinstanceOfType(myForm);

在你的情况下,myForm实际上是typeof(BaseClass),它是未记录的类型RuntimeType(派生自Type),因此如果这个未记录的类型恰好从提供的类型派生,你只会返回true – 这是不太可能是理想的行为.

我应该用什么呢?

您可能会追溯的是is keword,如果提供的对象是给定类型的实例,则返回true

derivedClass is BaseClass
baseClass is DerivedClass
myClass is MyClass

今天关于issubclasss/type/isinstance/callable/super的介绍到此结束,谢谢您的阅读,有关Build-in Function:abs(),all(),any(),assii(),bin(),issubclass(),bytearray(),isinstance()、C# IsAssignableFrom与IsSubClassOf 判断匿名类是否继承父类、c# – Type.IsSubclassOf()在AppDomains中不起作用?、c# – 什么时候是obj.GetType().IsInstanceOfType(typeof(MyClass))是真的吗?等更多相关知识的信息可以在本站进行查询。

本文标签: