【python中的对象属性】教程文章相关的互联网学习教程文章

Python属性和字符串格式【代码】

我在印象python字符串格式使用.format()将正确使用属性,而我得到一个字符串格式的对象的默认行为:>>> def get(): return "Blah" >>> a = property(get) >>> "{a}!".format(a=a) '<property object at 0x221df18>!'这是预期的行为,如果是的话,什么是实现属性的特殊行为的好方法(例如,上面的测试将返回“Blah!”而不是)?解决方法:属性对象是描述符.因此,除非通过课程访问,否则他们没有任何特殊能力. 就像是:class Foo(object):@p...

python TypeError:’NoneType’对象没有属性’__getitem__’【代码】

这次我尝试从Solem’s blog开始的另一个例子.它是一个通过使用Hough变换检测图像中的线条和圆圈的模块.这是代码(houghlines.py):import numpy as np import cv2""" Script using OpenCV's Hough transforms for reading images of simple dials. """# load grayscale image im = cv2.imread("house2.jpg") gray_im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)# create version to draw on and blurred version draw_im = cv2.cvtCol...

python – 内置函数和用户定义函数的不同属性【代码】

有这个代码:def f():passprint("f: ", dir(f)) print("len: ", dir(len))输出:f: ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne_...

Python中初始化实例属性(三)【代码】

尽管我们可以自由地给一个实例绑定各种属性,但是,现实世界中,一种类型的实例应该拥有相同名字的属性。例如,Person类应该在创建的时候就拥有 name、gender 和 birth 属性,怎么办? 在定义 Person 类时,可以为Person类添加一个特殊的__init__()方法,这里我们称为构造函数。当创建实例时,构造函数的方法被自动调用,我们就能在此为每个实例都统一加上以下属性: class Person(object):def __init__(self, name, gender, birth)...

python – Tkinter,’module’对象没有属性’Frame’【代码】

我在tkinter python中写了一个hello world app,但我接下来的消息:’module’对象没有属性’Frame’import _tkinter as tk这是错误class Application(tk.Frame):def __init__(self, master=None):tk.Frame.__init__(self, master)self.pack()self.createWidgets()def createWidgets(self):self.hi_there = tk.Button(self)self.hi_there["text"] = "Hello World\n(click me)"self.hi_there["command"] = self.say_hiself.hi_there....

python – AttributeError’module’没有属性’Queue’【代码】

我正在尝试导入队列,并且我继续获得以下内容Traceback (most recent call last):File "threading.py", line 2, in <module>import QueueFile "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/Queue.py", line 5, in <module>import threading as _threadingFile "/Users/zaq/threading.py", line 10, in <module>queue = Queue.Queue() AttributeError: 'module' object has no attribute 'Queue'我正在使用链接...

Python中的线程:类属性(列表)不是线程安全的?【代码】

我试图理解Python中的Threads. 代码 现在我遇到了一个问题,我在一个简单的课程中包含了这个问题:# -*- coding: utf-8 -*- import threadingclass myClassWithThread(threading.Thread):__propertyThatShouldNotBeShared = []__id = Nonedef __init__(self, id):threading.Thread.__init__(self)self.__id = iddef run(self):while 1:self.dummy1()self.dummy2()def dummy1(self):if self.__id == 2:self.__propertyThatShouldNotB...

Python 2.7 – AttributeError:’module’对象没有属性’load’【代码】

我使用的是Python 2.7,不知道为什么我一直收到这个加载错误?import pickle f=open("C:\\Users\\James\\Desktop\\banner.p",'rb') storedlist=pickle.load(f) for i in storedlist:print (i)Traceback (most recent call last):File "C:/Users/James/Desktop/pickle.py", line 1, in <module>import pickleFile "C:/Users/James/Desktop\pickle.py", line 3, in <module>storedlist=pickle.load(f) AttributeError: 'module' objec...

Python打印对象的全部属性【图】

__dict__方法遇到这样一个情况,要打印出一个对象的各种属性。但是不同对象的属性名都不一样,结构也不同,无法写一个代码来实现。然后我找到了__dict__,使用这个属性,可以动态获取到对象的所有属性,不包括公用属性。 通过__dict__,就可以动态的获取到对象的全部属性。获得的是一个字典,属性名是字典的key,属性值是字典的value。从输出看,私有属性也可以获得,只是不包括公有属性。然后,如果只想要属性值的话,可以对字典再...

Python 3.5 pip 9 AttributeError:’NoneType’对象没有属性’bytes’【代码】

问题是什么?我尝试了“python -m pip install -U pip”和“python -m pip install –upgrade pip”两者都有相同的错误(和“pip install -U –force-reinstall pip”).我该怎么办?C:\Users\Peyman\PycharmProjects\untitled3>python -m pip install -U pip Collecting pipUsing cached https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3af41213346e5b6c221c9e086a166f3703d2ddaf940/pip-18.0-py2.py3-none-any.w...

python – AttributeError:’Tensor’对象没有属性’numpy’【代码】

如何修复此错误我从GitHub下载了此代码.predicted_id = tf.multinomial(tf.exp(predictions), num_samples=1)[0][0].numpy()抛出错误AttributeError: 'Tensor' object has no attribute 'numpy'请帮我解决这个问题! 我用了:sess = tf.Session()with sess.as_default():predicted_id = tf.multinomial(tf.exp(predictions), num_samples=1)[0][0].eval()我得到这个错误.有人帮助我,我只是想让它工作为什么这么难?D:\Python>pytho...

python – Django ManyToMany FIeld:’tuple’对象没有属性’user’【代码】

有一点django问题我坚持…我的型号:class Mymodel(models.Model):[...]user = models.ManyToManyField(User)我尝试在其上创建新用户mymodel = Mymodel.objects.get_or_create(date=date, day=day, time=time) # This one gives a solid Mymodel object i can play with mymodel.user.add(user) # User is a instance of the Django User System当试图执行时,它会抛出’tuple’对象没有属性’user’ 我不小心把它变成了一个元组吗?...

python – 创建一个类级装饰器以自动添加属性【代码】

我想创建一个类级装饰器,它自动向对象添加属性,包括适当的getter和setter方法以及一个后备变量.例如:@autoproperty("foo", can_get=True, can_set=True, allow_null=False, default_value=0) @autoproperty("baz", can_get=True, can_set=False, allow_null=True, default_value=0) @autoproperty("bar") class SomeNonTrivialClass(object):def __init__(self):#lots of stuff going on heredef discombobulate(self):#this is o...

python – 访问__setattr__中的对象属性【代码】

Python今天咬了我一下.我试图在其__setattr__实现中访问对象的属性 – 我无法弄清楚如何.这是我到目前为止所尝试的:class Test1(object):def __init__(self):self.blub = 'hi1'def __setattr__(self, name, value):print self.blubclass Test2(object):def __init__(self):self.blub = 'hi2'def __setattr__(self, name, value):print object.__getattr__(self, 'blub')class Test3(object):def __init__(self):self.blub = 'hi3'...

我们如何在Python中获得可选的类属性?【代码】

对于字典,我们可以使用.get方法.类的属性怎么样并提供默认值?解决方法:您可以使用hasattr和getattr. 例如:hasattr(foo, 'bar')如果foo具有名为bar的属性,则返回True,否则返回False和getattr(foo, 'bar', 'quux')如果存在则返回foo.bar,否则默认为quux.