In Python you can add members dynamically to an object, but (1) the name must already exist (it must have been assigned) and (2) it must be bound to an instance of some class. To do so you may create an empty class:
class Empty:
pass # empty statement otherwise the class declaration cannot succeed
construct an instance of it and assign it to your variable
person = Empty()
and then add whatever data you want
person.name = 'Mike'
person.age = 25
person.gender = 'male'
On the other hand, if you don't need the additional features a "normal" class provides and you just want to store some data in a key=>value fashion you should probably just use a dictionary.
person={}
person['name']='Mike'
person['age']=25
person['gender']='male'
(notice that, at least up to Python 2.7, this is mostly just a stylistic/syntactic difference, since instance members are implemented underneath in terms of dictionaries)
As a general guideline, you want classes when you are instantiating multiple objects made in the same way (and where typically the assignment to the members is done in the class constructor; adding members later generally makes for difficult to follow code), dictionaries otherwise.
Answer from Matteo Italia on Stack OverflowIn Python you can add members dynamically to an object, but (1) the name must already exist (it must have been assigned) and (2) it must be bound to an instance of some class. To do so you may create an empty class:
class Empty:
pass # empty statement otherwise the class declaration cannot succeed
construct an instance of it and assign it to your variable
person = Empty()
and then add whatever data you want
person.name = 'Mike'
person.age = 25
person.gender = 'male'
On the other hand, if you don't need the additional features a "normal" class provides and you just want to store some data in a key=>value fashion you should probably just use a dictionary.
person={}
person['name']='Mike'
person['age']=25
person['gender']='male'
(notice that, at least up to Python 2.7, this is mostly just a stylistic/syntactic difference, since instance members are implemented underneath in terms of dictionaries)
As a general guideline, you want classes when you are instantiating multiple objects made in the same way (and where typically the assignment to the members is done in the class constructor; adding members later generally makes for difficult to follow code), dictionaries otherwise.
Python won't magically create a container object when you start assigning attributes to it, and if matlab allows this, I'd consider matlab badly broken. Consider this:
person.name = "Mike"
persom.age = 25
person.sex = "Male"
Now we have two objects, person and persom, and person doesn't have age, and there was no hint that this happened. Later you try to print person.age and, one would hope, matlab then complains... two pages after the actual mistake.
A class can itself be used as a container or namespace. There's no need to instantiate it, and it'll save you a bit of typing if you just want a bundle of attributes.
class sex:
male = "M"
female = "F"
class person:
name = "Mike"
age = 25
sex = sex.male
To access or modify any of these, you can use person.name, etc.
N.B. I used a class for sex as well to illustrate one of the benefits of doing so: it provides consistency in data values (no remembering whether you used "M" or "Male" or "male") and catches typos (i.e. Python will complain about sex.mlae but not about the string "mlae" and if you were later checking it against "male" the latter would fail).
Of course, you still run the risk of misspelling name, age, or sex in this type of class definition. So what you can do is use the class as a template and instantiate it.
class Person:
def __init__(self, name, age=None, sex=None):
self.name, self.age, self.sex = name, age, sex
Now when you do:
person = Person("Mike", 25, sex.male)
or if you want to document what all those parameters are:
person = Person("Mike", age=25, sex=sex.male)
it is pretty much impossible to end up with an object that has a misspelled attribute name. If you mess it up, Python will give you an error message at the point you made the mistake. That's just one reason to do it this way.
In Python, we learn that in order to create a class you need to start off with the `class` keyword. But the reality is that we actually don't.
I've written an article on how this works. We take a deeper dive into data types in Python and explore how they work under the hood.
I explore how all data types are classes, and how they can all be derived from `type` which by the way can do more than tell you the type of an object! Check out the article below if this sounds intriguing.
https://medium.com/@Salaah01/creating-a-class-in-python-without-the-class-keyword-67ce84bae22
Edit: Oh, and don't worry. The point of the article isn't to say. "Hey guys, this is a new way to write classes, and this is what you should do from now on". In the article, I explicitly discourage that. Instead, it's to give an inside to how it works and why it works.
How do I create an object that has no class in Python? - Stack Overflow
design - Can you implement "object-oriented" programming without the class keyword? - Software Engineering Stack Exchange
How is this code creating objects without constructors or instance attributes? Please see the description
Can I create a class without constructor? (details in the post)
You can use static or class methods for classes:
class MyClass:
@classmethod
def my_func(cls, p1, p2):
return [p1, p2]and then you can call it like this: MyClass.my_func(1, 2)
I hope this is what you asked.
https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner
More on reddit.comVideos
Congratulations! You rediscovered the well known fact that object orientation can be done without specific programming language support. It is basically the same way objects are introduced in Scheme in this classic text book. Note that Scheme does not have a class keyword or some kind of equivalent, and objects can be created without having even classes.
However, the object orientated paradigm was so successful that lots of languages - and Python is no exception - provide built-in support for it. This is simply to make it easier for developers to use the paradigm and to provide a standard form of object orientation for that language. It is essentially the same reason why lots of languages provide a for loop, though it could be emulated using a while loop with just one or two additional lines of code - simply ease of use.
I would agree that the first definition satisfies the three points your teacher made. I do not think we need the class keyword for anything. Under the covers, what else is an object but a data structure with with different types of data and functions to work with the data? Of course, the functions are data as well..
I would go even further and say that doing object oriented programming is not so much dependent on the keywords your language provides, you can do object oriented programming in C if you so wished! In fact, the linux kernel employs such techniques.
What you can infer from the class keyword here is, that the language provides support for this kind of construct out of the box, and you do not need to through all the hoops to re-implement the functionality yourself(which is pretty fun task in itself!). Not to mention all the syntactic sugar you might get as well.
I'm working with Flask and using SQL Alchemy ORM and there is something I would like to understand in the code. SQLAlchemy allows the creation of model class by extending the db.Model And in the model class we declare class attributes instead of instance attributes. Why is that ?
We don't even have a constructor or __init__ method and yet we are able to create objects by passing arguments (and that too on the freaking class attributes). How is this working ?
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
app = Flask(name) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db = SQLAlchemy(app)
class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) password = db.Column(db.String(60), nullable=False)
def __repr__(self):
return f"User('{self.username}', '{self.email}')"with app.app_context(): db.create_all()
# how is the user getting created here with any init method in the User class user1 = User(username="foo", email="foo@demo.com", password="foobar") print(user1) db.session.add(user1) db.session.commit() print(User.query.all())
Hi!
When I need data to have a special structure and special properties I can create a custom object and its constructor in a custom class without problem. I can create methods in the class to do stuff with the object as well. That I have done and can do just fine.
Now I have a set of functions that only take numbers (some floats, some integers) as argument and return numbers (usually in an array). Can I still put them in a class if the class has no constructor? Is it better to come up with something that could be an object and to create a class with a constructor for this object + the functions that now will be applied to this object?
At the moment my program works just fine but I'm self-taught and I obviously didn't do it the right way. I'm just using it to automate things so that's fine but I may have to give it to people, which is why I'd like to improve and to rewrite it more clean.
Thanks in advance for your help!
You can use static or class methods for classes:
class MyClass:
@classmethod
def my_func(cls, p1, p2):
return [p1, p2]
and then you can call it like this: MyClass.my_func(1, 2)
I hope this is what you asked.
https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner
In Python 3 all classes have constructors, the only question is does that constructor do anything of value.
That said, can you perhaps try and better explain what you're trying to accomplish, and what you're asking?
It sounds like you're describing functions that have no reason to be in a class at all. They're already in the module's namespace, so why bundle them together of methods of an otherwise do-nothing class?