Python init self master

Что обозначает этот простой код?

Когда делаешь
class Application(Frame):
то Application — это твой самодельный класс, который делается из существующего класса Frame.

Это значит, что все объекты (экземпляры) класса Application будут двух типов одновременно — типа Application и типа Frame.

Когда делаешь
def __init__(self, master):
это значит, что ты у класса Application делаешь метод __init__. При этом у класса Frame есть свой собственный метод __init__. Эти методы могут полностью различаться.

Когда делаешь
app = Application(root)
ты создаёшь объект (экземпляр) класса Application. При этом ему в метод __init__ передаётся основное окно всей программы.

app имеет сразу два типа — самодельный Application (который ты сам сделал) и существующий Frame (который уже сделали до тебя). По правилам tkinter’а, когда ты создаёшь какое-нибудь окно, его надо прилеплять к основному (так можно давать команды сразу всему дереву окон, в котором одни окна прилеплены к другим, и всё это прилеплено к основному окну).

Так вот, чтобы было всё правильно, твой самодельный объект, который сделан из существущего оконного типа, нужно прилепить к основному окну. Но так как твой объект — самодельный и сам по себе окном не является, то внутри себя он должен обратиться к тому типу, который делает его окном, и передать ему основное окно программы, чтобы тот мог к нему прилепиться.

Читайте также:  Php is callable function

Понимаешь, у тебя app — это один объект как бы двух типов: один тип не делает ничего, в нём есть только свой __init__ и ещё там какой-то самодельный метод; а другой тип является окном со всеми методами и свойствами окна.
Поэтому, чтобы в своём самодельном типе что-то делать, ты обращается просто к его элементам. А чтобы в существующем типе что-то делать, ты к нему получаешь доступ через super() (от слова суперкласс), а потом обращаешься к своим же элементам но через методы другого типа.

Поэтому запись
super(Application, self).__init__(master)
Означает, что нужно взять метод __init__ у базового класса Frame и передать в него аргумент master, переданный в __init__ производного класса Application.
Функция super() как бы отыскивает базовый класс у класса Application и возвращает его, а дальше уже идёт обращение к методу __init__ этого найденного класса.

Источник

Understanding the Use of master and master=none Parameters in Python’s Init Function

Is it possible to form a class that comprises an unordered set with a template type identical to itself? This class accepts a parent widget as a parameter, which is optional and defaults to being passed to all new instances of the class upon initialization.

What is the purpose of master and master=none in an init function in python?

I suppose the rationale behind it could be similar to my own. What is the purpose of having a master? Additionally, why is it occasionally referred to as «master» and other times listed as «master = none»?

class Application(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.grid() self.createWidgets() 

The information I am referring to is from John W. Shipman’s book on creating GUIs in Python using Tkinter version 8.5. However, the documentation provided uses Python 2 while I will be using Python 3. I am wondering if I need to use the master version. I encountered another issue when trying to add a custom argument after the master argument. The error message stated that I cannot add a non-default argument after a default one. I am unsure of how to fix this. Shouldn’t the default argument, which is self, be listed first?

def __init__(self, master=None,inputDict): tk.Frame.__init__(self, master) self.grid(sticky=tk.N+tk.S+tk.E+tk.W) self.createWidgets() def createWidgets(self,inputDict): top=self.winfo_toplevel() top.rowconfigure(0, weight=1) top.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) tempDict = <> for k,v in inputDict.items(): if 1 

Your Application class is a subcategory of tk.Frame and has an optional parent widget parameter ( master ). If unspecified, none will be used as the default value for this parameter. This parameter will be supplied to the newly created instance of the Application class during initialization.

Take a look here for more info.

Singleton Class in Java, To create a singleton class, we must follow the steps, given below: 1. Ensure that only one instance of the class exists. 2. Provide global access to that …

MasterClass Live with Dan Brown

In his first-ever online class , best-selling author Dan Brown teaches his step-by-step process for turning ideas into gripping narratives, crafting intriguin

How to properly define a class object in tkinter

As part of my Python3 learning, I am currently working on creating a canvas that consists of an oval and a button. My aim is to enable the oval's width to increase upon clicking the button. Although the button and oval are displaying correctly, clicking the button does not yield the desired outcome and instead generates error message error message.

Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\amjones20\AppData\Local\Programs\Python\Python36-32\Lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:/Users/amjones20/PycharmProjects/gui/guiPractice1.py", line 13, in oval_change Canvas.itemconfigure(self, oval, width=3) NameError: name 'oval' is not defined 

The oval_change function doesn't seem to acknowledge self.oval in the __init__ function. Defining oval correctly is crucial for its recognition when the oval_change function is invoked. The code is provided below.

from tkinter import * class GUI(Canvas): def __init__(self, master): self.canvas = Canvas(master, width=600, height=600) self.canvas.pack() self.oval = self.canvas.create_oval(100,500,500,100) def oval_change(self): Canvas.itemconfigure(self, oval, width=3) def button_appear(self): self.button1 = Button(root, text="button", command=self.oval_change) self.button1_window = self.canvas.create_window(200, 200, window=self.button1) root = Tk() hex = GUI(root) hex.button_appear() root.mainloop() 

Let me clarify that this issue is not related to tkinter. The initialization rules for tkinter classes are similar to those for any other python class.

class GUI(Canvas): def __init__(self, master): self.canvas = Canvas(master, width=600, height=600) self.canvas.pack() 

A class is being defined which is inherited from Canvas , however, the constructor of the superclass is not being called properly resulting in incomplete construction.

You are creating a new canvas within the existing canvas.

As your custom class is already a Canvas , there is no requirement to produce an additional canvas. All you have to do is initialize the class appropriately and use the instance itself to construct the oval.

class GUI(Canvas): def __init__(self, master): Canvas.__init__(self, master, width=600, height=600) self.oval = self.create_oval(100,500,500,100) 

The error message indicates name 'oval' is not defined because you're only generating self.oval and not oval . To resolve this issue, apply self.oval instead. Moreover, it's preferable to invoke the method on self instead of the class.

def oval_change(self): self.itemconfigure(self.oval, width=3) 

The responsibility of placing the canvas in the window should lie with the code that creates it, eventually.

hex = GUI(root) hex.pack(fill="both", expand=True) 

Here is the complete program:

from tkinter import * class GUI(Canvas): def __init__(self, master): Canvas.__init__(self, master, width=600, height=600) self.oval = self.create_oval(100,500,500,100) def oval_change(self): self.itemconfigure(self.oval, width=3) def button_appear(self): self.button1 = Button(self, text="button", command=self.oval_change) self.button1_window = self.create_window(200, 200, window=self.button1) root = Tk() hex = GUI(root) hex.pack(fill="both", expand=True) hex.button_appear() root.mainloop() 

Interacting with the Master Page from the Content Page, Open the Site.master master page and add a Label and a GridView control to the leftContent

. Clear out the Label's Text property, set its …

Grails: how to define a master-detail view with grails constraints

My goal is to establish a basic view that showcases the master/detail relationship between the following tables:

create table MASTER_ID2 ( ID int not null, VALOR varchar(40), primary key (ID) ); create table DETAIL_ID2 ( ID int not null, ID_MASTER int not null, VALOR_DET char(40), primary key (ID) ); alter table DETAIL_ID2 add constraint FK_RDET5 foreign key (ID_MASTER) references MASTER_ID2 (ID) on delete restrict on update restrict; 

I have these domain classes:

class MasterId2 < Integer id String valor // static hasMany = [details : DetailId2] static mapping = < table 'master_id2' version false id generator:'identity', column:'ID' // details column: 'id_master' >static constraints = < id(max: 2147483647) valor(size: 0..40) >String toString() < return "$" > > class DetailId2 implements Serializable < Integer id Integer id_master String valor_det // MasterId2 master static belongsTo = MasterId2 static mapping = < table 'detail_id2' version false id generator:'identity', column:'ID' >static constraints = < id(max: 2147483647) valor_det(size: 0..40) >String toString() < return "$" > > 

However, the detail view fails to allocate a foreign key.

Integer id String valor // static hasMany = [details : DetailId2] static mapping = < table 'master_id2' // version is set to false, because this isn't available by default for legacy databases version false id generator:'identity', column:'ID' // details column: 'id_master' 
static constraints = < id(max: 2147483647) valor(size: 0..40) >String toString() < return "$" > 

The Serializable interface is implemented by the DetailId2 class.

Integer id Integer id_master String valor_det // //MasterId2 master //static belongsTo = MasterId2 static belongsTo = [master: MasterId2] static mapping = < table 'detail_id2' // version is set to false, because this isn't available by default for legacy databases version false id generator:'identity', column:'ID' // master insertable: false // enforce foreign key master updateable: false // enforce foreign key 
static constraints = < id(max: 2147483647) valor_det(size: 0..40) >String toString() < return "$" > 

Listbox without any values under the Master category.

Alter the mapping for DetailId2.

Manage units of measure - Supply Chain Management, To define rules for conversions between units of measure, follow these steps. Create or select the unit to define conversion rules for. On the …

Class with an unordered set of itself

In essence, I am wondering if it's possible to generate a class that contains a unordered set with a template type that is the class itself. To illustrate, suppose I want to create a Square class with a reference to an unordered set of adjacent squares. However, I encountered a difficulty when attempting to incorporate a hash function into the class definition. Below is the code I have so far.

#include #include #define SIZE 200 #define MASTER 0 class Square; namespace std < template<>struct hash  < std::size_t operator () (Square const &v) const < return v.r; >>; > class Square < public: int c1, c2; int r; std::unordered_set*neigh; Square() < neigh = new std::unordered_set(); > ~Square() < delete neigh; >bool operator==(const Square& second) < return this->r == second.r && this->c1 ==second.c1 && this->c2 == second.c2; > >; int main(int argc, char *argv[]) < Square sq; Square tt; sq.neigh->insert(tt); > 

Attempts were made to compile with g++ and FLAGS = --std=c++17 -Wall -Wextra -Wno-unused-parameter -Wno-unused-variable -ggdb, but a vast error message ensued, commencing with:

test.cpp: In member function ‘std::size_t std::hash::operator()(const Square&) const’: test.cpp:15:20: error: invalid use of incomplete type ‘const class Square’ 15 | return v.x; 

Uncertainty clouds my judgment on the appropriate course of action for this scenario. It is worth noting that the code presented is a simplified version of my requirements, yet the inclusion of a "neighbors" field is crucial.

To address your inquiry, simply define std::hash::operator() before the Square declaration without executing it.

namespace std < template<>struct hash < std::size_t operator() (Square const &) const; >; > 

Following the definition of Square , proceed to define std::hash::operator() .

namespace std < std::size_t hash::operator() (Square const& v) const < // return calculation >> 

In addition to the issue with insert , it seems that duplicating an object with a pointer and then deleting the same pointer twice is causing a problem. To fix this, consider using std::unique_ptr> as it will generate a compilation error if an attempt is made to copy it.

class Square< public: std::unique_ptr> neigh; Square() : neigh()> <> // no destructor needed bool operator==(const Square& second) const < // should be const // . >>; 

Following that, you will be required to arrange the objects using move .

sq.neigh->emplace(. constructor arguments. ); 

Java - Grails: how to define a master-detail view with, i make this changes. class MasterId2

Источник

Оцените статью