所以我有一个关于python的字典:
structure = dict()
我想知道如何实现这样的目标:
structure.my_func(parameters);
my_func
是我的自定义函数。
所以我以某种方式扩展了它的功能,我知道我们可以使用原型制作JavaScript。
在python上可能吗?如果是,怎么办?
谢谢。
答案 0 :(得分:4)
如注释中所述,定义python dict
类的子类:
class MyDict(dict):
def __init__(self):
super().__init__()
def my_method(self):
# do what you want here
答案 1 :(得分:2)
Python提供了You have chosen option 1
The side of the square is 2
The square area is 4
The square perimeter is 8
Thank you!
模块,以帮助程序员定义自定义容器。您应该将#include <stdio.h>
#define PI 3.14
#include <locale.h>
#include <string.h>
int square_functions (int side, int *area_square, int *perimeter);
float circle_functions (float radius, float * area_circle, float * circumference);
int write_on_file (int value);
int main()
{
float radius, area_circle, circumference;
int side, area_square, perimeter,choice;
//setlocale(LC_ALL, "spanish");
while (1)
{
printf("\nPress 1 to calculate the square\n");
printf("Press 2 to calculate the circumference\n");
printf("Enter your choice:\n");
scanf("%d",&choice);
write_on_file (choice);
switch (choice)
{
case 1:
printf("Please enter the side of the square: ");
scanf("%d", &side);
write_on_file (side);
if(side > 0)
{
square_functions (side, &area_square, &perimeter);
printf("\nSquare area: %d", area_square);
printf("\nSquare perimeter: %d\n", perimeter);
}
else
{
printf("The value is invalid; the operation has been canceled");
}
break;
case 2:
printf("\n\nPlease enter the radius of the circle: ");
scanf("%f", &radius);
if(radius > 0)
{
circle_functions (radius, &area_circle, &circumference);
printf("\nCircle area: %f", area_circle);
printf("\nCircumference: %f", circumference);
}
else
{
printf("The value is invalid; the operation has been canceled");
}
break;
}
}
return 0;
}
int square_functions (int side, int * area_square, int * perimeter)
{
* area_square = side * side;
* perimeter = side * 4;
write_on_file (*area_square);
write_on_file (*perimeter);
return 0;
}
float circle_functions (float radius, float * area_circle, float * circumference)
{
* area_circle = PI * radius * radius;
* circumference = 2 * PI * radius;
write_on_file (*area_circle);
write_on_file (*circumference);
return 0;
}
int write_on_file (int value)
{
FILE * fich;
fich=fopen("file.txt","a+");
fprintf(fich,"%d\n",value);
fclose(fich);
return 0;
}
用于只读容器,或将collections.abc
用于可变容器。
根据用例,从那些抽象基类继承要比直接从真实的collection.abc.Mapping
继承要容易得多。