![]() When you use the class keyword, Python creates this object automatically. Since classes are objects, they must be generated by something. > print(M圜lass()) # you can create an object from this classīut it's not so dynamic, since you still have to write the whole class yourself. > print(M圜lass) # the function returns a class, not an instance return Foo # return the class, not an instance Since classes are objects, you can create them on the fly, like any object.įirst, you can create a class in a function using class: > def choose_class(name): > print(ObjectCreatorMirror.new_attribute) > ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable > ObjectCreator.new_attribute = 'foo' # you can add attributes to a class > print(hasattr(ObjectCreator, 'new_attribute')) > echo(ObjectCreator) # you can pass a class as a parameter you can pass it as a function parameterĮ.g.: > print(ObjectCreator) # you can print a class because it's an object.This object (the class) is itself capable of creating objects (the instances),īut still, it's an object, and therefore: ![]() The instruction > class ObjectCreator(object):Ĭreates in memory an object with the name ObjectCreator. Classes are objects too.Īs soon as you use the keyword class, Python executes it and createsĪn object. That's kinda true in Python too: > class ObjectCreator(object):īut classes are more than that in Python. In most languages, classes are just pieces of code that describe how to produce an object. And Python has a very peculiar idea of what classes are, borrowed from the Smalltalk language. Before understanding metaclasses, you need to master classes in Python.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |