How to define custom Object name for instance of created class? - python

Python everything is object. We do find the name of the object we are using type() builtin method.
If I create class as follows
class Sample:
pass
a=Sample()
type(a)
returns as __main__.Sample
Here I want it to be print the name of object of my choice, how do I do that.
Ex: type({})
return Dict
I want to name object instance of my custom class

One can use module to replace main in type of the class instance,
i.e
class Sample():
__module__='custom'
type(Sample()) returns custom.Sample

I think I figured it out with existing python packages,
i.e
in pandas, it has DataFrame class or object when you define variable to this object and type of it returns pandas.core.frame.DataFrame. Here DataFrame is the class and pandas.core.frame is the module name of the class
so one can define his object name with replacing __main__ only i.e as shown below
class Sample():
__module__='Custom'
a=Sample()
print(type(a))
prints==> < class Custom.Sample>

Related

We can create instance attrbitues for objects in Python. Can we create instance methods (not class Methods) as well in Python?

How To create a methods which are common to a particular object just like creating instance attrbitue obj.instance_attribute
A method which belongs specifically for a single object ?
The link contains the code. I need to create method only for this object and not all instance of class.
Creating class methods and attribute. The instance attrbitue. How to create instance methods
class A():
def init(self):
self.class_variable = 999999
def class_methods(self):
#available to all object
print("Hey")
obj = A()
obj.class_variable
999999
obj.class_methods()
Hey
obj.instance_attribute = 40404040 #common to particular object
obj.instance_attribute
40404040
#a method which is common to only this object
obj.new_method():
SyntaxError: invalid syntax
obj.new_mehtod(self):
SyntaxError: invalid syntax
I think you are mixing up terminology. Every "normal" method is a instance method - that means it applies the function without affecting any other instances of this class. To reference the instance, use the passed self keyword.
Defining a method for a single instance inside the generator/ class definition does not make sense in an OOP-context. If you create a car class, every instance of this class should be able to access its methods, like drive().
The only way to add a unique function is to add it after instantiating the object. This can be done with the types.MethodType method, which binds the function to the class instance:
from types import MethodType
def fly(self):
print(f"i, {self.name}, can fly")
class Car:
def __init__(self, name):
self.name = name
car_1 = Car("car one")
car_2 = Car("car two")
car_1.fly = MethodType(fly, car_1)
car_1.fly() # i, car one, can fly
car_2.fly() # AttributeError: 'Car' object has no attribute 'fly'
As you can see, car_1 has the class fly, which references car_1's name, while car_2 does not have this function.
But you should seriously reconsider what you are trying to achieve here.

How can I see the class name here?

After going through some lectures on class and objects, what I have understood is that if a function is a part of a class then it can be accessed by object which is known as method and if a function is outside a class, then it can be accessed directly.
So for example -
1)
def introduce():
return 'My name is Joseph'
student1 = introduce()
Here since introduce is not within any class , we directly used introduce function and the result shall be 'My name is Joseph' which shall be stored in student1
2)
class room():
def introduce(self):
return 'My name is Joseph'
student1 = introduce()
a = student1.introduce()
Here this introduce function is inside room class and therefore to use it we have to associate a object with a class and then use it
Now going by this lets take an example of Pandas
we have a function named as - pandas.read()
I think pandas is a class but then here does it mean that pandas is a object and a read() is a function inside pandas ? Am I missing something ?
Shouldn't this be the case ?
df = pandas() # making an object of pandas class
df.read() # then accessing the read function inside pandas class
Kindly assist me
There are 3 types of functions(methods) you can have inside an python class.
Instance Method
Class Method
Static Method
Here's a thing to see that what you have created the method named introduce inside room that is "Instance Method". Which takes object as self parameter meaning which can be accessed by Instance(object).
You can also define a Class Method in following way.
class room():
#classmethod
def introduce(self):
return 'My name is Joseph'
This can be accessed as
room.introduce()
If you want to know about more about what is static or class methods. Visit here Check out
Note: The website has no connection to me I just found this online and I liked it so shared it ;)

Python: Create a member that is a instance of its class

I am very confused that I did not directly found a topic about my concern:
I got the class RoadMark. In this class, I wanna create a member that is a specific instance of that class. But I am not able to call the constructor.
I tried:
calling the init function (but it has no return, so its worthless)
define the member as a function with the #property attribute (but these returns cannot have members, so worthless for an object)
Trying "solid = self.RoadMark..." (also not working)
Using a factory function to create the object (but in the method, RoadMark is also not defined)
Is there a way to solve my problem or do I have to outsource the "solid" variable?
Kind regards
You can assign it to the class member after the class definition.
class RoadMark:
...
RoadMark.solid = RoadMark()
Python code is executed as it is encountered. When the interpreter encounters the line class RoaMark:, it starts creating a new class object. Then it starts to run the code inside the class body to determine the attributes of the class. When the code in the body is running, the class object does not exist yet, so you can't access it. What you can do is wait until the class is created before assigning an attribute to it:
class RoaMark:
...
RoaMark.solid = RoaMark(...)

How to access class module from object instance?

I want to access module-level variables of the module that defines the class the instance is derived from. I only have the instance to work from. I tried self.__class__.__module__[<some var>] but unlike the __class__ attribute which returns the class object, __module__ just returns a string name, not the module object itself. How can I get the module object in this situation?
The __module__ attribute can be used as a key in the sys.modules dictionary:
import sys
class_module = sys.modules[instance.__class__.__module__]

Getting a object stored in a dict by a string key

I successfully print a list of keys to the screen and then ask the user to type in a key name to get a specific object. This is the way i thought it worked:
print dict['bob']
and this would output the object stored with the 'bob' key however it does not. I'm assuming this problem arises because im storing objects and not strings or ints. If the name entered is a key it just prints the name again not the object and if it isn't a key it throws an error. The end result of this is to get a specified object so the user can view that objects attributes.
When the above statement is ran it just prints the key to the screen:
bob
printing my dictionary looks like this
{'Sal': <Employ_Class2.Employee object at 0x01EE38F0>, 'bob': <Emplo
y_Class2.Employee object at 0x01EE3930>, 'jack': <Employ_Class2.Employee o
bject at 0x01EE3990>, 'alexa': <Employ_Class2.Employee object at 0x01EE3870>,
'dave': <Employ_Class2.Employee object at 0x01EE3910>, 'sew
': <Employ_Class2.Employee object at 0x01EE3950>, 'tam': <Employ_Class2.Em
ployee object at 0x01EE39D0>}
It looks like you're simply being misled by the fact that print obj prints the result of calling the object's __str__ or __unicode__ methods. So, the object in the dictionary under the key "bob", when converted to string, is simply "bob".
As others have said, if you simply want to print the attributes of the object under that key, use dir:
obj = dict['bob']
print dir(obj)
If you want to view the names of the attributes of the object, use dir().
If the dictionary contains the instances of the class you've created and you want to extract relevant information from those objects, you need to create in your class a function which does that and invoke it later.
Suppose you have an object of type Product, given that Product is the class you've created. You store multiple products in your dictionary. What do you want to get back? The name of the product? The name, the price and the description? Or maybe the class name? Python won't be able to figure out your intention, so it's up to you to either create a specific method which does what you want it to do, or use __str__().
I think what you wanted is dir([object]) .
Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
So according to the documentation you can have the attributes fro that object with dir().
Hope this is what you have wanted..
Not sure if you are referring to object attributes you are defining in your class definition or the names you would find with dir(). In either case, if your object class has a __str__ or __repr__ methods defined, those will be called when using print. If you want a user to be able to view the names in the object space, just use dir(). If you want them to access attributes and properties you set in the class definition, access them directly (or through whatever methods you created to do so:
class Test:
attr = 'item' # this is a class attribute
def __init__(self):
self.name = 'Me' # this will be an instance variable/property
def __str__(self):
return self.name
d = {} # example does not need a dict but using one to relate to posted question
d['item'] = Test()
print(d['item'])
results in self.name being printed to screen:
dir(d['item']) will instead print out all of the names in the object namespace, including methods and attributes.
To print your created attributes (attr and self.name above), then you can simply do:
print(d['item'].attr)
print(d['item'].name)
So, in that case, your users should just access the dict objects directly: dict['bob'].attribute
Hope that makes some sense.

Categories

Resources