New object in python | SoloLearn: Learn to code for FREE!

+5

New object in python

Hi. Can we add new object to our python program? E.g: a= <'a','b','c'> >>> type(a) output: class UserDefined

4/7/2020 11:02:45 AM

Ramin.RX7

17 Answers

New Answer

+10

Sure. Ex https://code.sololearn.com/cuUZdc9KhHu0/?ref=app

+5

Sousou has provided a way to do that, simply add [print(type(x))] at the bottom of the code and see the output.. if you're talking about the template <"a", "c", "."> system like it used to in c# or java, then that won't be possible

+5

Ramin.RX7 To create such type of new things is quite hard, it's called extension and I'm still learning so I won't be able to provide a code for that. It can only be done using the C language so you may need to learn C as core to get started, just Google for "how to create python extensions"...you'll see a lot of result ig

+4

what the hell are u doing there???? It seems to be a cool hack

+4

There's a way creating an object on the fly, using the type function, for example like this: myobj = type('MyType', (object,), dict(a=1, b=2, c=3))() print(myobj) print(myobj.a) That what you're talking about?

+4

Oh, wait, do you mean, you want to invent a new *literal* for your type? So that, just as you can write... l = [] d = {} s = '' ... you could write this... x = <1, 2, 3> ... and it would become an instance of your own type? That would be similar to operator overload, maybe 'delimiter overload'? Okay, I think we can't do that. That would be quite fancy. 😁

+4

Folks I like this question very much but forgot to upvote. 😉

+3

In python you cannot create your own symbols like that. There is some fancy stuff like the matmul operator @ which is used (implemented) exclusively by numpy. You can override it with magic methods same as other operators. But <> cannot be used like this. In some programming languages like Lisp or Haskell you have more freedom to define such symbols.

+2

You can inherit from builtin types, would that do the trick? class MyList(list): ... And then define whatever you want to add or override, everything else remaining just like list.

+1

thank you Sousou and HonFu . But I knew these trick. I just wanted to make a new type of object that can make it simple like lists with another type name.

+1

Go through https://www.w3schools.com/python/python_classes.asp

0

But in code dont use the tags '< >'

0

You may find answer in https://www.tutorialspoint.com/How-to-append-objects-in-a-list-in-Python

0

you just create a new class that’s what class is a blueprint for objects https://www.programiz.com/python-programming/class

0

Yes this class is over viewing the pass lreanson

0

is it a question? please provide your tips as a block. dont post in QNA section. Have a nice coding.

0

S bro it is easy good idea