【day18_python_类关系】教程文章相关的互联网学习教程文章

python – 类的价值是多少?【代码】

在reference manual中,声明每个对象都有一个类型,一个标识和一个值:Every object has an identity, a type and a value.例如,这些看起来很简单:x = 10 # type(x) = int, id(x) = some address, value = 10至少,我怀疑value = 10是真的. 对于类,类型和ID再次易于查找:class Foo:def __init__(self, a):self.a = a# type(Foo) = type # id(Foo) = some address但是,什么被认为是这个对象的价值?它的属性和方法?解决方法:Python语...

是否值得确保不调用不可调用的Python类?【代码】

如果是的话,你能建议比下面更好的方式吗?请详细说明/证明.class X:...if __name__ == '__main__':# TODO: Should we bother doing this?errorMessage = 'This class is not meant to have a main method. Do not execute directly.'print(errorMessage)raise Error(errorMessage)解决方法:我不会这样做. 原因如下:python -i scriptname.py可用于加载脚本并放到运行脚本的交互式控制台后.那么你得到的是所有已定义的函数,然后你可...

是否可以使用带参数的Python类装饰器?【代码】

我想做的是:@add_cache(cache_this, cache_that, cache_this_and_that) class MyDjangoModel(models.Model):blah但失败是因为看起来第一个参数隐含了实际的类对象.有可能解决这个问题,还是我被迫使用丑陋的语法而不是这种美妙的语法?解决方法:您的arg_cache定义需要执行以下操作:def arg_cache(cthis, cthat, cthisandthat):def f(obj):obj.cache_this = cthisobj.cache_that = cthatobj.thisandthat = cthisandthatreturn objr...

Python类实例__dict__不包含所有实例变量.为什么?【代码】

这里有一个关于实例变量的新手Python问题. 考虑以下Python 2.7类定义:class Foo(object):a = 1def __init__(self):self.b = 2def __repr__(self):return "%s" % self.__dict__现在,当我创建一个Foo实例时,Foo .__ dict__包含b,但不是a.>>> x=Foo() >>> x {'b': 2} >>> dir(x) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduc...

python – 在类中使用super()【代码】

我试图以这种方式使用super()作为一个简单的类层次结构:class Employee(object):def __init__(self, name):self.name = nameclass FullTime(Employee):def __init__(self, name, satOff, freeDays=[], alDays=[], programDays=[]):global satsOffDictglobal dayDictsuper(Employee, self).__init__(name)但是,我收到此错误:TypeError: object.__init__() takes no parameters我已经读过你需要创建父对象类型对象(新样式类)才能让...

声明python类,并创建类实例. (核心Python编程)【代码】

我正在学习“核心python编程第2版”中的python 我陷入了“如何创建类实例”部分.第84页. 示例如下: classes.py:class FooClass(object):"""my very first class: FooClass"""version = 0.1 # class (data) attributedef __init__(self, nm='John Doe'):"""constructor"""self.name = nm # class instance (data) attributeprint'Created a class instance for', nmdef showname(self):"""display instance attribute and class n...

Python – 由类和实例变量混淆【代码】

我试着为unix find-command编写一个小的包装器脚本.我搞砸参数传递的东西.你能否给我一个关于我的错误的暗示? 错误消息是Traceback (most recent call last):File "frep.py", line 43, in <module>inst.prep_shell_commands(self.extension, self.search_string, self.rel_numbers) NameError: name 'self' is not defined这是代码:import os import subprocess import string import sysclass Frep(object):extension = ""searc...

python – 类不识别属性?【代码】

这真让我抓狂.我希望程序打印名称“Frank”.但是,我收到一条错误,上面写着“AttributeError:’People’对象没有属性””.我在网上搜索过,据我所知,我做的一切都是正确的,但是因为我得到了一个错误,显然我不是. 我正在使用Python 2.class People(object):def __init__(self, name):self.name = namedef called(self):return self.namefrank = People("Frank")print frank.called()我做错了什么?解决方法:看起来像是缩进问题.圆点是...

python类之特殊属性和魔术方法【代码】【图】

一 python特殊属性 1 总述属性 含义_name_ 类,函数,方法等的名字_module_ 类定义所现在的模块名_class_ 对象或类所属的类_bases_ 类的基类的元素,顺序为他们在基类列表中出现的顺序_doc_ 类/函数的文档字符传,如果没有定义则为None_mro_ 类的mro,class.mro()返回_dict_ 类或实例的属性,可写的字典_dir_ 返回了类或者对象所有成员列表,dir()函数调用的是_dir_(),如果提供了_dir_(),则返回属性列表,否则尽可能从__dict__属...

python类层次结构的问题【代码】

我有一个类层次结构:class ParentClass:def do_something(self):pass # child classes have their own implementation of thisclass ChildClass1(ParentClass):def do_something(self):<implementation here>class ChildClass2(ParentClass):def do_something(self, argument_x):<implementation here>class ChildClass3(ParentClass):def do_something(self, argument_y):<implementation here>这里有两个问题: >方法do_somethi...

在另一个python类中使用未绑定的方法【代码】

我有一个未绑定的方法作为< unbound方法foo.ops>,我想与另一个类使用相同的方法.举个例子class foo2(object):passfoo2.ops = foo.ops然而obj = foo2() obj.ops()raises TypeError: unbound method ops() must be called with foo instance as first argument (got nothing instead)解决方法:如果要将相同的方法添加到多个不相关的类(例如,执行AOP),请不要从其中一个中复制未绑定的方法.相反,定义一个普通函数并将其作为方法分配给每...

python – 类`object`的实例【代码】

我希望创建一个内置类对象的实例,并将其用作某些变量的容器(如C中的struct):Python 3.2 (r32:88445, Mar 25 2011, 19:56:22) >>> a=object() >>> a.f=2 Traceback (most recent call last):File "<stdin>", line 1, in <module> AttributeError: 'object' object has no attribute 'f'有没有办法比这样做更容易实现:>>> class struct(): ... '''Container''' ... >>> a=struct() >>> a.f=2 >>> a.f 2 >>> 更新: >我需要一...

python类的简单使用

class Person:def __init__(self, name , age):self.name = nameself.age = agedef print_name(self):print("my name is %s"%self.name)def print_age(self):print("my age is {}".format(self.age))pTest = Person("Bob", "25") print("这是类实例化后的内存地址:%s"%pTest) pTest.print_name() pTest.name = "Make" pTest.print_age()

创建一个被视为列表但具有更多功能的python类?【代码】

我有一个名为dataList的类.它基本上是一个包含一些元数据的列表—myDataList.data包含(numpy)列表本身,myDataList.tag包含描述等.我希望能够使myDataList [42]返回myDataList的相应元素.数据,我想让Numpy等将它识别为一个列表(IE,numpy.asarray(myDataList)返回一个包含myDataList中数据的numpy数组).在Java中,这就像将dataList声明为实现List接口一样简单,然后只定义必要的函数.你会怎么用Python做到这一点? 谢谢.解决方法:您可以...

python – 类的多个实例【代码】

我有一个名为Points的课程,我需要创建100分.我需要做类似的事情:class Point(object) ...for i in range(1,100):pi = Point()这些点应命名为p1,p2,… p100 显然,上面的行不起作用. 问题是:我知道我可以在一个循环中使用exec来创建100个点但是有没有更好的方法可以在不使用exec的情况下完成它?解决方法:您可以使用列表推导创建多个对象:# 100 points in list points = [Point() for _ in range(100)]