GVKun编程网logo

Python __setattr__、 __getattr__、 __delattr__、__call__用法(python setattribute)

2

在这篇文章中,我们将带领您了解Python__setattr__、__getattr__、__delattr__、__call__用法的全貌,包括pythonsetattribute的相关情况。同时,

在这篇文章中,我们将带领您了解Python __setattr__、 __getattr__、 __delattr__、__call__用法的全貌,包括python setattribute的相关情况。同时,我们还将为您介绍有关'super' 对象没有属性 '__getattr__',谁能帮帮我?、AttributeError: 'super' 对象在 python 和 kivy 代码中没有属性 '__getattr__'、Difference between __getattr__ vs __getattribut...、Kivy AttributeError: 'super' 对象没有属性 '__getattr__'(尝试了所有以前的解决方案)的知识,以帮助您更好地理解这个主题。

本文目录一览:

Python __setattr__、 __getattr__、 __delattr__、__call__用法(python setattribute)

Python __setattr__、 __getattr__、 __delattr__、__call__用法(python setattribute)

getattr

`getattr`函数属于内建函数,可以通过函数名称获取
代码如下:
value = obj.attribute
value = getattr(obj, “attribute”)

使用`getattr`来实现工厂模式
代码如下:
#一个模块支持html、text、xml等格式的打印,根据传入的formate参数的不同,调用不同的函数实现几种格式的输出

import statsout

def output(data, format=”text”):
output_function = getattr(statsout, “output_%s” %format)
return output_function(data)

__call__

`__call__`方法用于实例自身的调用:
代码如下:
class storage(dict):
# __call__方法用于实例自身的调用
#达到()调用的效果
def __call__ (self, key):
try:
return self[key]
except KeyError, k:
return None

s = storage()
s[‘key’] = ‘value’
print s(key) #调用__call__

__getattr__

从对象中读取某个属性时,首先需要从self.__dicts__中搜索该属性,再从__getattr__中查找。

代码如下:
class A(object):
def __init__(self):
self.name = ‘from __dicts__: zdy’

def __getattr__(self, item):
if item == ‘name’:
return ‘from __getattr__: zdy’
elif item == ‘age’:
return 26

a = A()
print a.name # 从__dict__里获得的
print a.age # 从__getattr__获得的

__setattr__

`__setattr__`函数是用来设置对象的属性,通过object中的__setattr__函数来设置属性:
代码如下:
class A(object):
def __setattr__(self, *args, **kwargs):
print ‘call func set attr’
return object.__setattr__(self, *args, **kwargs)

__delattr__

`__delattr__`函数式用来删除对象的属性:
代码如下:
class A(object):
def __delattr__(self, *args, **kwargs):
print ‘call func del attr’
return object.__delattr__(self, *args, **kwargs)

例子

完整例子可以参考微博API:http://github.liaoxuefeng.com/sinaweibopy/
代码如下:
class _Executable(object):

def __init__(self, client, method, path):
self._client = client
self._method = method
self._path = path
#__call__函数实现_Executable函数对象为可调用的
def __call__(self, **kw):
method = _METHOD_MAP[self._method]
if method==_HTTP_POST and ‘pic’ in kw:
method = _HTTP_UPLOAD
return _http_call(‘%s%s.json’ % (self._client.api_url, self._path), method, self._client.access_token, **kw)

def __str__(self):
return ‘_Executable (%s %s)’ % (self._method, self._path)

__repr__ = __str__

class _Callable(object):

def __init__(self, client, name):
self._client = client
self._name = name

def __getattr__(self, attr):
if attr==’get’:
       #初始化_Executable对象,调用__init__函数
return _Executable(self._client, ‘GET’, self._name)
if attr==’post’:
return _Executable(self._client, ‘POST’, self._name)
name = ‘%s/%s’ % (self._name, attr)
return _Callable(self._client, name)

def __str__(self):
return ‘_Callable (%s)’ % self._name

__repr__ = __str__

而在源码中,存在下面代码片段:

代码如下:
class APIClient(object):
”’
API client using synchronized invocation.
”’

def __getattr__(self, attr):
if ‘__’ in attr:
return getattr(self.get, attr)
return _Callable(self, attr)

因此,加入我们初始化对象,并调用某函数如下:
代码如下:
client = APIClient(…)
#会调用__getattr__函数,从而调用__call__函数
client.something.get()

'super' 对象没有属性 '__getattr__',谁能帮帮我?

'super' 对象没有属性 '__getattr__',谁能帮帮我?

如何解决''super'' 对象没有属性 ''__getattr__'',谁能帮帮我??

进口:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.textinput import TextInput
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager,Screen
from kivy.uix.Boxlayout import BoxLayout
kv = ''''''

<Login>
    ben: benName.text
    pw: passwort.text
    knopf: btn
    knopff: btnn
 
    GridLayout:
        cols: 1
        size: root.width,root.height
        GridLayout:
            cols: 2
            Label:
                text: "Username"
                font_size: 25
            TextInput:
                id: benName
                multiline: False
                font_size: 30
            Label:
                text: "Password"
                font_size: 25
                bold: True
            TextInput:
                password: True
                id: passwort
                multiline: False
                font_size: 40
        Button:
            size_hint: (1.,1.10)
            text:" Start "
            id: btn
            font_size: 40
            on_release:
                root.manager.current = "Readed" if passwort.text == "1" and benName.text == "1" else "login"
                root.manager.transition.direction = "down"
        Button:
            size_hint: (1.,1.10)
            text: " Exit "
            id: btnn
            font_size: 40
            on_release: app.stop()






<readed>:
    BoxLayout:
        orientation: ''vertical''
        TextInput:
            id: text_field
        Button:
            text: ''click''
            on_press: app.read()

''''''

MyApp 类:

class Login(Screen):
    ben = Stringproperty()
    pw = Stringproperty()
    knopf = Objectproperty()


class MyApp(App):
    Builder.load_string(kv)
    def read(self):
        file = open("read.txt",''r'')
        f = file.readlines()
        self.root.ids.text_field.text = (''''.join(f))
        text = StringProperty("read.txt")
    def build(self):
        ms = ScreenManager()
        ms.add_widget(Login(name=''login''))
        ms.add_widget(Readed(name=''Readed''))
        self.title = "MyApp"
        return ms





class Readed(Screen):
    pass




if __name__ == ''__main__'':
    MyApp().run()
# her is the erorr
 #exec(__kvlang__.co_value,idmap)
   #File "<string>",line 59,in <module>
   #File "C:\Users\---\--\Desktop\B-PYTHON\----\TEST 45.py",line 93,in read
     #self.root.ids.text_field.text = (''''.join(f))
   #File "kivy\properties.pyx",line 864,in kivy.properties.ObservableDict.__getattr__
 #AttributeError: ''super'' object has no attribute ''__getattr__''
#[Finished in 5.9s with exit code 1]

解决方法

代码行:

self.root.ids.text_field.text = (''''.join(f))

正在尝试访问应用根目录的 ids。但是应用程序根是 ScreenManager,它没有 ids(因为它没有出现在 kv 中)。这就是导致错误的原因。

修复方法是访问 ids ReadedScreen,因为这是定义 text_field 的地方。尝试类似:

self.root.get_screen(''Readed'').ids.text_field = (''''.join(f))

由于 rootScreenManager,您可以使用 get_screen() 获取对 Readed Screen 的引用。获得该引用后,您可以使用 idsScreen 中定义的 kv

AttributeError: 'super' 对象在 python 和 kivy 代码中没有属性 '__getattr__'

AttributeError: 'super' 对象在 python 和 kivy 代码中没有属性 '__getattr__'

如何解决AttributeError: ''super'' 对象在 python 和 kivy 代码中没有属性 ''__getattr__''?

您好,我在使用 kivy 时遇到了这个错误。我的目的是创建我的应用程序的登录屏幕,用于检查用户输入的数据是否正确。但是这样做时,我一次又一次地收到此错误。



我的代码如下:

Python 文件:

from kivy.lang import Builder
from kivymd.app import MDApp  
import MysqL.connector as ms
from kivy.properties import StringProperty,NumericProperty
from kivy.uix.screenmanager import ScreenManager,Screen


acc = NumericProperty("")
pw = StringProperty("")

class safarapp(MDApp):
    def build(self):
        self.theme_cls.theme_Dark''
        self.theme_cls.primary_palette = ''BlueGray''
        return
        
    def Login(self):
            self.acc = self.root.ids.acc_num.text
            
            self.pw = self.root.ids.password.text
            
            host = ms.connect(
              host="localhost",user="root",password="bhawarth20",database="safar"
              )
              
            cur = host.cursor(buffered = True)
            
            
            
            cur.execute("Select * from data where Account_Number = %s and Password = %s collate utf8mb4_bin",(self.acc,self.pw))
            data="error" #initially just assign the value
            
            for i in cur:
                data=i #if cursor has no data then loop will not run and value of data will be ''error''
                if data== "error":
                    print("User Does not exist")
                else:
                    print("User exist")

class LoginScreen(Screen):
    pass
    
    
class SignUpScreen(Screen):
    pass


sm = ScreenManager()
sm.add_widget(LoginScreen(name= "login"))
sm.add_widget(SignUpScreen(name= "signup"))



                    
                    
if __name__ == ''__main__'':
    safarapp().run()

KV 文件:


ScreenManager:
    LoginScreen:
    SignUpScreen:


<LoginScreen>:
    name: ''login''
    MDCard:
        size_hint: None,None
        size: 300,400
        pos_hint: {''center_x'': .5,''center_y'': .5}
        elevation:10
        spacing: 25
        padding: 25
        orientation: ''vertical''
        
        MDLabel:
            text: "Safar Login"
            font_size: 40
            halign: ''center''
            size_hint_y: None
            height: self.texture_size[1]
            padding_y: 10
            pos_hint: {''center_y'': 1}

        MDTextField:
            id: acc_num
            hint_text: ''Account Number''
            icon_right: ''account''
            max_text_length: 6
            size_hint_x: None
            pos_hint: {''center_x'': .5}
            width: 200
            font_size: 18
            required: True
                        
        MDTextField:
            id: password
            hint_text: ''Password''
            password: True
            size_hint_x: None
            pos_hint: {''center_x'': .5}
            width: 200
            font_size: 18
            icon_right: ''eye''
            required: True
            
        MDFillRoundFlatButton:
            id: Login
            text: ''Login''
            size_hint_x: None
            pos_hint: {''center_x'': .5}
            width: 200
            elevation: 10
            on_release: app.Login()

            
        MDFillRoundFlatButton:
            id: Sign_Up
            text: ''Sign Up''
            size_hint_x: None
            pos_hint: {''center_x'': .5}
            width: 200
            elevation: 10
            on_release: root.manager.current = ''signup''
            
                
<SignUpScreen>:
    name: ''signup''
    MDLabel:
        text: "Hello World!!!"

这是我得到的错误:

[INFO   ] [Logger      ] Record log in C:\Users\Welcome\.kivy\logs\kivy_21-07-12_51.txt
[INFO   ] [deps        ] Successfully imported "kivy_deps.angle" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.glew" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.3.1
[INFO   ] [Kivy        ] v2.0.0
[INFO   ] [Kivy        ] Installed at "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\__init
py"
[INFO   ] [Python      ] v3.8.2 (tags/v3.8.2:7b3ab59,Feb 25 2020,22:45:29) [MSC v.1916 32 bit (Intel)]
[INFO   ] [Python      ] Interpreter at "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\python.exe"
[INFO   ] [Factory     ] 186 symbols loaded
[INFO   ] [KivyMD      ] 0.104.2,git-bc7d1f5,2021-06-06 (installed at "C:\Users\Welcome\AppData\Local\Programs\Python\python3
2\lib\site-packages\kivymd\__init__.py")
[INFO   ] [Image       ] Providers: img_tex,img_dds,img_sdl2,img_pil (img_ffpyplayer ignored)
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [Window      ] Provider: sdl2
[INFO   ] [Window      ] Activate GLES2/ANGLE context
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] Backend used <angle_sdl2>
[INFO   ] [GL          ] OpenGL version <b''OpenGL ES 2.0.0 (ANGLE 2.1.13739 git hash: 385fb40fd460)''>
[INFO   ] [GL          ] OpenGL vendor <b''Google Inc.''>
[INFO   ] [GL          ] OpenGL renderer <b''ANGLE (Mobile Intel(R) 965 Express Chipset Family Direct3D11 vs_4_0 ps_4_0)''>
[INFO   ] [GL          ] OpenGL parsed version: 2,0
[INFO   ] [GL          ] Shading version <b''OpenGL ES GLSL ES 1.00 (ANGLE 2.1.13739 git hash: 385fb40fd460)''>
[INFO   ] [GL          ] Texture max size <8192>
[INFO   ] [GL          ] Texture max units <16>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed,single mode,not docked
[INFO   ] [GL          ] NPOT texture support is available
[INFO   ] [Base        ] Start application main loop
[INFO   ] [Base        ] Leaving application in progress...
 Traceback (most recent call last):
   File "kivy\properties.pyx",line 861,in kivy.properties.ObservableDict.__getattr__
 KeyError: ''acc_num''

 During handling of the above exception,another exception occurred:

 Traceback (most recent call last):
   File "D:\my projects of python\Safar\safar.py",line 69,in <module>
     safarapp().run()
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\app.py",line 950,in run
     runTouchApp()
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\base.py",line 582,in runTouchApp
     EventLoop.mainloop()
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\base.py",line 347,in mainloop
     self.idle()
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\base.py",line 391,in idle
     self.dispatch_input()
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\base.py",line 342,in dispatch_inpu
     post_dispatch_input(*pop(0))
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\base.py",line 308,in post_dispatch
put
     wid.dispatch(''on_touch_up'',me)
   File "kivy\_event.pyx",line 709,in kivy._event.Eventdispatcher.dispatch
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivymd\uix\behaviors\ripple_behavior.py",ne 296,in on_touch_up
     return super().on_touch_up(touch)
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivymd\uix\button.py",line 981,in on_to
_up
     return super().on_touch_up(touch)
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\uix\behaviors\button.py",line 179,on_touch_up
     self.dispatch(''on_release'')
   File "kivy\_event.pyx",line 705,in kivy._event.Eventdispatcher.dispatch
   File "kivy\_event.pyx",line 1248,in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx",line 1132,in kivy._event.EventObservers._dispatch
   File "C:\Users\Welcome\AppData\Local\Programs\Python\python38-32\lib\site-packages\kivy\lang\builder.py",line 57,in custom
llback
     exec(__kvlang__.co_value,idmap)
   File "D:\my projects of python\Safar\safar.kv",line 56,in <module>
     on_release: app.Login()
   File "D:\my projects of python\Safar\safar.py",line 27,in Login
     self.acc = self.root.ids.acc_num.text
   File "kivy\properties.pyx",line 864,in kivy.properties.ObservableDict.__getattr__
 AttributeError: ''super'' object has no attribute ''__getattr__''

请帮助我尽快解决此错误。任何帮助将不胜感激。

解决方法

您的代码:

    self.acc = self.root.ids.acc_num.text
    self.pw = self.root.ids.password.text

正在尝试访问不在 ids root 字典中的 ids。这些 ids<LoginScreen>: 规则中定义,因此它们出现在 LoginScreen 实例中。将这两行替换为:

    login_screen = self.root.get_screen(''login'')
    self.acc = login_screen.ids.acc_num.text
    self.pw = login_screen.ids.password.text

Difference between __getattr__ vs __getattribut...

Difference between __getattr__ vs __getattribut...

A key difference between __getattr__ and __getattribute__ is that __getattr__ is only invoked if the attribute wasn''t found the usual ways. It''s good for implementing a fallback for missing attributes, and is probably the one of two you want.

__getattribute__ is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly. You can end up in infinite recursions very easily.

New-style classes derive from object, old-style classes are those in Python 2.x with no explicit base class. But the distinction between old-style and new-style classes is not the important one when choosing between __getattr__ and __getattribute__.

Kivy AttributeError: 'super' 对象没有属性 '__getattr__'(尝试了所有以前的解决方案)

Kivy AttributeError: 'super' 对象没有属性 '__getattr__'(尝试了所有以前的解决方案)

如何解决Kivy AttributeError: ''super'' 对象没有属性 ''__getattr__''(尝试了所有以前的解决方案)?

这是 Python 中最烦人的错误之一,根据问题有很多解决方案

我的文件

Main.py

# imports
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen,ScreenManager


# Defining Screen,ScreenManager And App Classes:
class MainScreen(Screen):
    pass


class ShortCuts(Screen):
    pass


class WindowManager(ScreenManager):
    pass


# Kivy Lang Builder Packed As A Variable
BLD = Builder.load_file("KV_FILE.kv")


class OnlineClassMacros(App):

    # Initializing The App
    def __init__(self,**kwargs):
        super(OnlineClassMacros,self).__init__(**kwargs)

    # Defining The App By Referencing The Packed Kivy.Lang.Builder Variable Created At The Start Of The .py File
    def build(self):
        return BLD

    @staticmethod
    def Get():
        query = BLD.ids.SearchEngine.text

        print(query)


# Todo: Monetize The >>Online Class Macros<< Application By Using KivMob


# MainLooping The Application Using  [if __name__ == "__main__":]
if __name__ == "__main__":
    OnlineClassMacros().run()

KV_FILE.kv

# Importing Our Function.py As A Python Module Into Kivy-Lang\

#######################################################
#:import redirect Function.redirect
#######################################################

# Pre-Styling Widgets
<Label>
    halign: ''center''
    valign: ''center''
    background_color: ''0'',''.4'',''.3'',''.4''
<Button>
    halign: ''center''
    valign: ''center''
    background_color: "0",".1",".8"

# Configuring The Screens And The Screen Manager
WindowManager:
    MainScreen:
    ShortCuts:

# Building All The Classes In Our "Main.py" File

<MainScreen>:
    name: "MainScreen"

    canvas.before:
        Rectangle:
            size: self.size
            pos: self.pos
            source: "Images/background 2.png"
    BoxLayout:
        orientation: "horizontal"
        BoxLayout:
            size_hint: .2,1
            orientation: "vertical"
            Button:
                text: "Google\nDocs"
                on_release: redirect("https://www.docs.google.com")
            Button:
                text: "Google\nSlides"
                on_release:
                    redirect("https://slides.google.com/u/0/h")
            Button:
                text: "Gmail"
                on_release:
                    redirect("https://www.gmail.com")
            Button:
                text: "Google\nClassroom"
                on_release:
                    redirect("https://classroom.google.com/u/0/")
        BoxLayout:
            size_hint: .6,1
            BoxLayout:
                orientation: "vertical"
                TextInput:
                    size_hint: 1,.2
                    multiline: True
                    hint_text: "Search here"
                    background_color: 1,1,.78
                    id: SearchEngine
                GridLayout:
                    cols: 3
                    Button:
                        text: "Google Scholar\nSearch"

                    Button:
                        text: "Wikipedia\nSearch"
                        on_release:
                            app.Get()
                    Button:
                        text: "Google\nSearch"
                    Button:
                        text: "RefSeek\nSearch"
                    Button:
                        text: "Microsoft Academic\nSearch"
                    Button:
                        text: "Hyper Search"
                        background_color: 1,.99
        BoxLayout:
            size_hint: .2,1
            orientation: "vertical"
            Button:
                text: "Google\nspreadSheets"
                on_release:
                    redirect("https://classroom.google.com/u/0/h")
            Button:
                text: "MicroSoft\nTeams"
                on_release:
                    redirect("https://classroom.google.com/u/0/h")
            Button:
                text: "OutLook"
                on_release:
                    redirect("https://classroom.google.com/u/0/h")



<ShortCuts>:
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.pos
            source: ''Images/ Background 3.png''

错误:

C:\Users\mayan\AppData\Local\Programs\Python\python39\python.exe "C:/Online Class Macros ;)/Main.py"
[INFO   ] [Logger      ] Record log in C:\Users\mayan\.kivy\logs\kivy_21-06-13_7.txt
[INFO   ] [deps        ] Successfully imported "kivy_deps.gstreamer" 0.3.2
[INFO   ] [deps        ] Successfully imported "kivy_deps.angle" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.glew" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.3.1
[INFO   ] [Kivy        ] v2.0.0
[INFO   ] [Kivy        ] Installed at "C:\Users\mayan\AppData\Local\Programs\Python\python39\lib\site-packages\kivy\__init__.py"
[INFO   ] [Python      ] v3.9.4 (tags/v3.9.4:1f2e308,Apr  6 2021,13:40:21) [MSC v.1928 64 bit (AMD64)]
[INFO   ] [Python      ] Interpreter at "C:\Users\mayan\AppData\Local\Programs\Python\python39\python.exe"
[INFO   ] [Factory     ] 186 symbols loaded
[INFO   ] [Image       ] Providers: img_tex,img_dds,img_sdl2,img_pil (img_ffpyplayer ignored)
[INFO   ] [Window      ] Provider: sdl2
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] GLEW initialization succeeded
[INFO   ] [GL          ] Backend used <glew>
[INFO   ] [GL          ] OpenGL version <b''4.0.0 - Build 10.18.10.5059''>
[INFO   ] [GL          ] OpenGL vendor <b''Intel''>
[INFO   ] [GL          ] OpenGL renderer <b''Intel(R) HD Graphics''>
[INFO   ] [GL          ] OpenGL parsed version: 4,0
[INFO   ] [GL          ] Shading version <b''4.00 - Build 10.18.10.5059''>
[INFO   ] [GL          ] Texture max size <16384>
[INFO   ] [GL          ] Texture max units <16>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed,single mode,not docked
[INFO   ] [GL          ] NPOT texture support is available
[INFO   ] [GL          ] Unpack subimage support is available
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [Base        ] Start application main loop
[INFO   ] [Base        ] Leaving application in progress...
 Traceback (most recent call last):
   File "kivy\properties.pyx",line 861,in kivy.properties.ObservableDict.__getattr__
 KeyError: ''SearchEngine''
 
 During handling of the above exception,another exception occurred:
 
 Traceback (most recent call last):
   File "C:\Online Class Macros ;)\Main.py",line 46,in <module>
     OnlineClassMacros().run()
   File "C:\Users\mayan\AppData\Local\Programs\Python\python39\lib\site-packages\kivy\app.py",line 950,in run
     runTouchApp()
   File "C:\Users\mayan\AppData\Local\Programs\Python\python39\lib\site-packages\kivy\base.py",line 582,in runTouchApp
     EventLoop.mainloop()
   File "C:\Users\mayan\AppData\Local\Programs\Python\python39\lib\site-packages\kivy\base.py",line 347,in mainloop
     self.idle()
   File "C:\Users\mayan\AppData\Local\Programs\Python\python39\lib\site-packages\kivy\base.py",line 391,in idle
     self.dispatch_input()
   File "C:\Users\mayan\AppData\Local\Programs\Python\python39\lib\site-packages\kivy\base.py",line 342,in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\mayan\AppData\Local\Programs\Python\python39\lib\site-packages\kivy\base.py",line 308,in post_dispatch_input
     wid.dispatch(''on_touch_up'',me)
   File "kivy\_event.pyx",line 709,in kivy._event.Eventdispatcher.dispatch
   File "C:\Users\mayan\AppData\Local\Programs\Python\python39\lib\site-packages\kivy\uix\behaviors\button.py",line 179,in on_touch_up
     self.dispatch(''on_release'')
   File "kivy\_event.pyx",line 705,in kivy._event.Eventdispatcher.dispatch
   File "kivy\_event.pyx",line 1248,in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx",line 1132,in kivy._event.EventObservers._dispatch
   File "C:\Users\mayan\AppData\Local\Programs\Python\python39\lib\site-packages\kivy\lang\builder.py",line 57,in custom_callback
     exec(__kvlang__.co_value,idmap)
   File "C:\Online Class Macros ;)\KV_FILE.kv",line 70,in <module>
     app.Get()
   File "C:\Online Class Macros ;)\Main.py",line 36,in Get
     query = BLD.ids.SearchEngine.text
   File "kivy\properties.pyx",line 864,in kivy.properties.ObservableDict.__getattr__
 AttributeError: ''super'' object has no attribute ''__getattr__''

Process finished with exit code 1

这个错误以前发生在我身上,我解决了它,但正如我所说,答案取决于问题。 如果没有人删除我的问题说它是重复的,我真的很感激。

解决方法

神秘的错误消息没有多大帮助,但堆栈跟踪显示错误发生在该行中:

query = BLD.ids.SearchEngine.text

此行失败的原因是您试图访问 id 对象中不存在的 SearchEngine (BLD)。 BLD 对象是您的 kv 的根,也就是 WindowManager,但 SearchEngine id 是在 <MainScreen>: 规则中定义的。因此,修复方法是通过正确的对象访问该 ID:

def Get():
    app = App.get_running_app()  # get a refrence to the running App
    main_screen = app.root.get_screen(''MainScreen'')  # get a reference to the MainScreen
    query = main_screen.ids.SearchEngine.text  # now use the id

    print(query)

请注意,documentation 表示:

当 kv 文件被处理时,weakrefs 到所有标记为 id 被添加到根小部件的 id 字典中。

该文档不正确。 ids 实际上是添加到包含 id 的规则的基础对象中,而不是添加到 kv 文件的根小部件中。

今天关于Python __setattr__、 __getattr__、 __delattr__、__call__用法python setattribute的介绍到此结束,谢谢您的阅读,有关'super' 对象没有属性 '__getattr__',谁能帮帮我?、AttributeError: 'super' 对象在 python 和 kivy 代码中没有属性 '__getattr__'、Difference between __getattr__ vs __getattribut...、Kivy AttributeError: 'super' 对象没有属性 '__getattr__'(尝试了所有以前的解决方案)等更多相关知识的信息可以在本站进行查询。

本文标签: